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 | 22

Highest age first.

Example 2 (sql)
SELECT name, country, age FROM users
ORDER BY country ASC, age DESC;
Output
sorted by country, then age

Multi-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.

๐Ÿ“ Quick Quiz

1. Default ORDER BY direction is:

2. How do you sort high to low?

3. `ORDER BY a, b DESC` sorts b: