SQL ORDER BY
ORDER BY sorts the result. Without it, the order rows come back in is undefined — even if it looks stable today.
Ascending vs descending
SQL
-- A → Z, oldest → newest (default) SELECT * FROM customers ORDER BY name ASC; -- Z → A, newest → oldest SELECT * FROM customers ORDER BY created_at DESC;
Multi-column sort
List columns in priority order — the second only breaks ties in the first:
SQL
SELECT * FROM customers ORDER BY country ASC, name ASC;
Sorting by position or expression
| Form | Notes |
|---|---|
ORDER BY 1, 2 | Sort by the first and second columns in the SELECT. Concise but brittle if you reorder columns. |
ORDER BY LOWER(name) | Sort by a computed expression — useful for case-insensitive sort. |
ORDER BY price * quantity DESC | Any expression works. |
Tip: Combine
ORDER BY with LIMIT (MySQL/Postgres) or TOP (SQL Server) to get the top-N rows: SELECT * FROM products ORDER BY price DESC LIMIT 10;.Example
Exercise
Sort customers by name from Z down to A.
SELECT * FROM customers ORDER BY name
;
Four letters; the descending direction.
Discussion
Loading…