iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

FormNotes
ORDER BY 1, 2Sort 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 DESCAny 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

Example
SELECT * FROM customers
ORDER BY country ASC, name DESC;
Try it Yourself »

Exercise

Sort customers by name from Z down to A.

SELECT * FROM customers ORDER BY name ;

Test yourself

Q1. Default sort direction is…
Q2. ORDER BY country, name means…
Q3. Without ORDER BY the row order is…

Discussion

Loading…