SQL ยท Chapter 6 of 42
SQL ORDER BY
ORDER BY sorts the result set by one or more columns.
Add `ASC` (default) or `DESC` per column.
Syntax
SELECT ... FROM table ORDER BY col1 ASC, col2 DESC;Multiple keys
`ORDER BY country ASC, age DESC` sorts by country AโZ, then by age highโlow within each country.
By expression
You can order by a computed expression or by column position (though position is fragile).
Example 1 (sql)
SELECT name, age FROM users ORDER BY age DESC;Output
name | age
Ben | 30
Ana | 25
Cara | 22Highest age first.
Example 2 (sql)
SELECT name, country, age FROM users
ORDER BY country ASC, age DESC;Output
sorted by country, then ageMulti-key sort.
Key points
- Default is ASC (ascending).
- DESC reverses order.
- Multiple keys separated by commas.
- NULLs sort first or last depending on dialect.
๐ก Note: Use `NULLS FIRST` / `NULLS LAST` (PostgreSQL, Oracle) to control where NULLs appear.
