SQL ORDER BY
Sort the result.
Syntax
SELECT … FROM … ORDER BY col1 [ASC|DESC], col2 [ASC|DESC];
ASC (smallest first) is the default; DESC sorts largest first. Later columns break ties in earlier ones. Without ORDER BY, row order is not guaranteed.
Example
Query (on the shop database used in the SQL course)
SELECT name, category, price FROM products ORDER BY category, price DESC;
Result
| name | category | price |
|---|---|---|
| Deep Learning (book) | Books | 89.0 |
| Python Crash Course (book) | Books | 45.0 |
| SQL Pocket Guide | Books | 25.0 |
| 27-inch monitor | Electronics | 329.0 |
| Noise-cancelling headphones | Electronics | 249.0 |
| Mechanical keyboard | Electronics | 119.0 |
| USB-C hub | Electronics | 49.0 |
| Wireless mouse | Electronics | 29.0 |
| Standing desk | Furniture | 549.0 |
| Ergonomic chair | Furniture | 399.0 |
| Desk lamp | Furniture | 59.0 |
| Coffee beans 1 kg | Grocery | 32.0 |
| Green tea, 100 bags | Grocery | 12.0 |
| Gel pens, pack of 10 | Stationery | 11.0 |
| A5 notebook | Stationery | 8.5 |
15 rows
Good to know. NULLs sort first in SQLite and last in PostgreSQL (add NULLS FIRST / NULLS LAST to choose).
Related
Learn it step by step in the free lesson SELECT: Choosing Columns, with exercises that check your queries.