SQL ORDER BY
Sort your query results in any order you need.
What is ORDER BY?
The ORDER BY clause sorts the rows returned by a SELECT query. Without ORDER BY, the database can return rows in any order — never assume a default order.
Basic syntax
Syntax
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC; -- ASC is the default
ASC vs DESC
SQL — customers A to Z
SELECT name, city
FROM customers
ORDER BY name ASC; -- alphabetical A→Z
SQL — most expensive orders first
SELECT id, product, amount
FROM orders
ORDER BY amount DESC; -- highest first
Sort by multiple columns
Separate with commas. The database sorts by the first column, then breaks ties with the second.
SQL
SELECT name, city, amount
FROM customers
JOIN orders ON customers.id = orders.customer_id
ORDER BY city ASC, amount DESC;
-- Sort by city A-Z, then within each city by amount (highest first)
Sort by column position
You can use the column number instead of its name:
SQL
SELECT name, city, amount
FROM customers
ORDER BY 3 DESC; -- order by 3rd column (amount)
Sort by expression
SQL
SELECT name, amount, amount * 0.18 AS tax
FROM orders
ORDER BY amount * 0.18 DESC;
NULL ordering
NULLs sort to the top with DESC and to the bottom with ASC in most databases. Force control with NULLS FIRST / NULLS LAST (PostgreSQL, Oracle):
SQL (PostgreSQL)
SELECT name, phone
FROM customers
ORDER BY phone ASC NULLS LAST; -- NULLs go at the very end
| Keyword | Effect |
|---|---|
ASC | Ascending (A→Z, 0→9, oldest→newest). Default. |
DESC | Descending (Z→A, 9→0, newest→oldest) |
NULLS FIRST | NULLs appear before non-NULLs |
NULLS LAST | NULLs appear after non-NULLs |
ORDER BY runs last
Execution order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY. This means you can sort by an alias defined in SELECT — e.g.,
SELECT amount * 0.18 AS tax ... ORDER BY tax DESC works.