Sorting, the first N, no repeats
Problem
Top 3 for the shop window
The owner wants the three most expensive products on the home page. You know how to get the name and the price. But in what order do the rows come, and how do you take just three?
The idea
ORDER BY
ORDER BY sorts the result. By default from small to large:
DESC reverses it, from large to small:
You can sort by several columns: first by the first, and on a tie by the second. Customers by city, and within a city by name:
Text sorts alphabetically, dates like 2026-10-19 by time.
More precisely, if you are curious
Without ORDER BY, the order of the rows is not promised. It often comes out by id, but that is an accident of how the database read the table. After a change to the table or with a new index, the order can change. When order matters to you, write ORDER BY.
The idea
LIMIT: only the first
LIMIT n returns the first n rows of the result. Together with ORDER BY it gives a top N:
LIMIT runs last, after sorting. That is why “the three most expensive” is right. Without ORDER BY it would be three random products.
OFFSET skips rows. That is how pages are made: the second page of orders, 10 per page:
Try it
The new customers
Show the name and sign-up date of the five newest customers, newest first.
Solution
SELECT name, joined_at FROM customers
ORDER BY joined_at DESC
LIMIT 5;ORDER BY joined_at DESC LIMIT 5. Here the check also looks at the order of the rows.
The idea
DISTINCT: no repeats
Which cities are the customers from? With SELECT city, each city repeats as many times as it has customers. DISTINCT removes the repeats:
Six cities and NULL: Boris has no city, and that absence is a separate result too.
Try it
The order statuses
Show all the different order statuses, in alphabetical order.
Solution
SELECT DISTINCT status FROM orders ORDER BY status;SELECT DISTINCT status FROM orders ORDER BY status. Five statuses: from cancelled to shipped.
Exercise
Cheap and in stock
Show the name, price and stock of the five cheapest products that are in stock, cheapest first.
Solution
SELECT name, price, stock FROM products
WHERE stock > 0
ORDER BY price
LIMIT 5;WHERE stock > 0 ORDER BY price LIMIT 5. The order of the parts matters: WHERE, then ORDER BY, finally LIMIT. Products that ran out are left out, even if they are cheaper.
More precisely, if you are curious
Where do NULLs go when sorting? In SQLite and MySQL, ORDER BY city puts them first; in PostgreSQL and Oracle they come last. If it matters, say so: ORDER BY city NULLS LAST. SQLite understands it since version 3.30.
Test