Sorting and deduplication
Without ORDER BY, SQL returns rows in whatever order it finds them, which could change between runs. ORDER BY gives you control: sort alphabetically, by price, by date, or by multiple columns.
-- Most expensive items first
SELECT product_id, price
FROM order_items
ORDER BY price DESC
LIMIT 10;
-- Multi-column sort: state ascending, then city ascending
SELECT customer_state, customer_city
FROM customers
ORDER BY customer_state ASC, customer_city ASC
LIMIT 20;DESC = descending (highest first). ASC = ascending (lowest first, this is the default). You can sort by multiple columns.
Sorting is useful, but sometimes you also have duplicate values cluttering your results. DISTINCT removes those duplicates so you can see only the unique values.
-- How many unique states do our customers come from?
SELECT DISTINCT customer_state
FROM customers
ORDER BY customer_state;
-- Unique order statuses
SELECT DISTINCT order_status
FROM orders;DISTINCT removes duplicate rows from your results. It considers ALL selected columns when determining uniqueness.
Yes, DISTINCT requires extra work to find and remove duplicates (usually sorting or hashing). On small result sets it is fine. On millions of rows, consider whether you actually need it. Sometimes the duplicates exist because your query logic needs adjusting, not because you need DISTINCT.
Ordering exercise: SQL execution order
Loading practice…
Quiz: Quiz
Loading practice…
Code playground: Top cities by customer count
Loading practice…