ORDER BY (ASC, DESC)
ORDER BY sorts query results by one or more columns. ASC (ascending) is the default — smallest to largest, A to Z. DESC (descending) — largest to smallest, Z to A. You can sort by multiple columns with different directions each.
ORDER BY Rules
- ORDER BY col ASC — ascending (default, can omit ASC)
- ORDER BY col DESC — descending (largest first)
- ORDER BY col1 ASC, col2 DESC — multi-column sort
- NULL values sort last in ASC, first in DESC (PostgreSQL) — varies by database
- ORDER BY col position: ORDER BY 2 sorts by the 2nd SELECT column
- Alias in ORDER BY is valid (unlike WHERE)
- ORDER BY is applied after WHERE and GROUP BY
ORDER BY Examples
-- Sort products cheapest first (ASC — default)
SELECT name, price FROM products ORDER BY price ASC;
-- Result: Headphones, Phone, Laptop
-- Sort products most expensive first
SELECT name, price FROM products ORDER BY price DESC;
-- Result: Laptop, Phone, Headphones
-- Sort orders by date (newest first)
SELECT id, status, created_at FROM orders
ORDER BY created_at DESC;
-- Multi-column: sort by status ASC, then price DESC within same status
SELECT name, price, stock FROM products
ORDER BY stock DESC, price ASC;
-- Sort by column position (2 = second column in SELECT)
SELECT name, price FROM products ORDER BY 2 DESC;
-- Sort by alias (valid in ORDER BY)
SELECT name, price * 0.9 AS sale_price
FROM products
ORDER BY sale_price ASC;
-- NULL values last (PostgreSQL)
SELECT name, stock FROM products
ORDER BY stock DESC NULLS LAST;Quick Quiz
Tip
Tip
Practice ORDER BY ASC DESC in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Not written order!
Common Mistake
Warning
A common mistake with ORDER BY ASC DESC is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready sql code.
Practice Task
Note
Practice Task — (1) Write a working example of ORDER BY ASC DESC from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Key Takeaways
- ORDER BY sorts query results by one or more columns.
- ORDER BY col ASC — ascending (default, can omit ASC)
- ORDER BY col DESC — descending (largest first)
- ORDER BY col1 ASC, col2 DESC — multi-column sort