ORDER BY

ORDER BY sorts the rows a query returns by one or more columns. By default it sorts ascending (smallest first); add DESC to sort descending.

SQL

You can sort by several columns at once — for example, by last name and then by first name. The first column is the primary sort, and later columns break ties.

ORDER BY runs after WHERE and grouping, so it sorts the final result set right before it is returned to you.

Syntax

SELECT columns FROM table_name ORDER BY column [ASC|DESC];

Examples

SQL

SELECT name, age
FROM users
ORDER BY age DESC;

Output:

name   age
-----  ---
Alice  30
Bob    22

Learn it in a lesson

See also

Back to the Dictionary