ORDER BY
Sorts the result rows by one or more expressions, ascending or descending.
Syntax
ORDER BY expression [ASC | DESC] [NULLS FIRST | NULLS LAST], ...ORDER BY is the only way to guarantee row order. It runs after SELECT, so it can use select-list aliases and column positions (ORDER BY 2).
ASC(default) sorts smallest first;DESClargest first. Each key has its own direction:ORDER BY category ASC, price DESC.- Later keys break ties in earlier ones. If the keys do not make every row unique, tied rows come back in an unpredictable order — add a unique column (usually the id) as the last key for a total order.
- NULL: PostgreSQL treats NULL as larger than every value: NULLs come last in
ASCand first inDESC. Override withNULLS FIRST/NULLS LAST. - You can sort by an expression not in the select list (
ORDER BY lower(name)) except withSELECT DISTINCT. - Text sorts by the database collation; with
ORDER BY name COLLATE "C"it sorts by byte value.
Examples
SELECT category, product_name, price
FROM products
ORDER BY category, price DESC, product_id;Categories A→Z; inside each category the most expensive first; product_id makes the order total.
SELECT customer_name, email
FROM customers
ORDER BY email NULLS FIRST, customer_id;Customers without an email appear first instead of last.
SELECT order_id, quantity * 10 AS points
FROM orders
ORDER BY points DESC, order_id
LIMIT 5;ORDER BY runs after SELECT, so the alias points is visible here (unlike in WHERE).
Pitfalls
Leaving ties unresolved and then relying on the order (top-N lists, pagination, graded results).
Expecting DESC to put NULLs last: in PostgreSQL DESC puts NULLs first unless you add NULLS LAST.
Sorting numbers stored as text: '10' sorts before '9'. Cast to a number first.
Using an alias inside an expression in ORDER BY (ORDER BY points * 2): only a bare alias is allowed.
Other databases
For orientation only: SQL Quest executes PostgreSQL.
- MySQL
NULLs sort first in ASC (opposite of PostgreSQL) and there is no NULLS FIRST/LAST; use ORDER BY col IS NULL, col.
- SQL Server
NULLs sort first in ASC; NULLS FIRST/LAST is not supported, use a CASE expression as the first key.
- SQLite
NULLs sort first in ASC; NULLS FIRST/LAST is supported since 3.30.
- Oracle
Same default as PostgreSQL (NULLs last in ASC) and supports NULLS FIRST/LAST.