🌱BeginnerFiltering & Sorting
ORDER BY
Sort query results by one or more columns in ascending or descending order.
Overview
ORDER BY sorts the rows returned by a SELECT. Without ORDER BY, the row order from a query is undefined it may appear consistent in small tables but can change without warning. Always specify ORDER BY when the order of results matters to the application or user.
You can sort by multiple columns (primary sort, then tiebreaker), use ASC (ascending, the default) or DESC (descending), and control where NULLs appear with NULLS FIRST or NULLS LAST. PostgreSQL lets you ORDER BY column aliases defined in the SELECT and even by positional column numbers (not recommended in production code).
Key Points
- •ORDER BY col ASC sorts smallest/earliest first (default)
- •ORDER BY col DESC sorts largest/latest first
- •Sort by multiple columns: ORDER BY col1 ASC, col2 DESC
- •NULLS FIRST / NULLS LAST controls where NULLs appear
- •Can reference SELECT aliases: SELECT price * 1.1 AS markup ... ORDER BY markup
- •Without ORDER BY, result order is undefined
Examples
Basic sorting
-- Sort by price ascending (cheapest first)
SELECT * FROM products ORDER BY price ASC;
-- Sort by created_at descending (newest first)
SELECT * FROM posts ORDER BY created_at DESC;
-- Sort by multiple columns
SELECT * FROM employees ORDER BY department ASC, salary DESC;NULL ordering
-- NULLs last (default for ASC)
SELECT * FROM products ORDER BY discount ASC NULLS LAST;
-- NULLs first
SELECT * FROM products ORDER BY discount DESC NULLS FIRST;Exercises
Write SQL to solve each exercise. Your progress is saved automatically.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4