SQL MDN Docs ORDER BY

ORDER BY clause in SQL

The ORDER BY clause in SQL is used to sort the result set of a query by one or more columns, either ascending (ASC) or descending (DESC). This is crucial when you need to organize data in a specific order for analysis or reporting.

Syntax

The basic syntax of the ORDER BY clause involves specifying the column or columns you want to sort by, followed by the direction of the sort.

Sorting data with ORDER BY

Single column sorting

To sort data by a single column, you can use the ORDER BY clause with the column name:

SELECT *
FROM users
ORDER BY age DESC

Multiple column sorting

You can also sort by more than one column. The sorting is performed on the first column specified, then on the next column within the previous sort, and so on:

SELECT *
FROM users
ORDER BY country ASC, age DESC

šŸ” Note that we sorted by the text column first (here the ASC order means from ā€œaā€ to ā€œzā€) and then by the numeric column.

Sorting data with the ORDER BY clause enhances readability and understandability of query results, which is particularly useful when presenting data to other people. šŸ“Š

It also plays a crucial role in preparing data for reporting and dashboards, ensuring that the data is in the expected format or order.

Additionally, during the exploratory phase of data analysis, sorting can help analysts quickly identify the highest or lowest values in a dataset, facilitating deeper investigations and insights.

Database compatibility

MySQL
PostgreSQL
SQLite
Redshift
Big Query
Snowflake
ORDER BY
ORDER BY
MySQL
PostgreSQL
SQLite
Redshift
Big Query
Snowflake

Find a problem on this page?

Want to get more involved? SQL MDN Docs is an open-source project, check out contribution guidelines.
This page was last modified on March 28, 2024.