Video in progress
How do you get the 3 most expensive products in each category with a single query?
With a window function: compute ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY price DESC) and filter rn <= 3 in the outer query. If equal prices must be included too, use DENSE_RANK or RANK.
📖 Answer
SELECT id, category_id, name, price
FROM (
SELECT p.*,
ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY price DESC) AS rn
FROM product p
) t
WHERE rn <= 3;
You can't use a window function directly inside WHERE, because it's computed after WHERE. That's why you need a subquery or CTE.
The three functions differ on equal values. If the prices are 100, 90, 90, 80:
| price | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 100 | 1 | 1 | 1 |
| 90 | 2 | 2 | 2 |
| 90 | 3 | 2 | 2 |
| 80 | 4 | 4 | 3 |
ROW_NUMBER numbers ties in arbitrary order, so to make the result stable, give it an extra key: ORDER BY price DESC, id.
If there are few categories and many products, another option runs faster: LATERAL:
SELECT c.id, p.*
FROM category c
CROSS JOIN LATERAL (
SELECT * FROM product
WHERE category_id = c.id
ORDER BY price DESC LIMIT 3
) p;
With a (category_id, price DESC) index, only 3 rows are read per category, and the whole table isn't sorted.
Sign up to mark studied questions and save your progress.