top n per group
the three best sellers in every category: row_number, LATERAL and DISTINCT ON, compared on one plan.
- address
- everything.analytics.top_n_per_group
- part
- part 4, windows, grouping and recursion
- chapter
- chapter 8 of 11
- reading time
- 7 min
"the best n of every group" is one of the most asked questions in SQL, and postgres has three answers. row_number in a subquery numbers every group and keeps the small numbers. LATERAL runs a little ORDER BY ... LIMIT n query once per group. DISTINCT ON keeps the first row of each group, so it only does n = 1.
same answer (mostly). different plans, and different winners as the data grows.
the picture
you know how ORDER BY units DESC LIMIT 3 gives you the three best sellers in the shop, and what you wanted was the three best sellers in each category? LIMIT cuts the whole result once. you need a cut per group.
think of a school sports day with ten events. you don't want the three fastest kids in the school, you want a podium per event. somebody has to line each event up separately and hand out three medals there.
units sold per product is an aggregate over 24,942 order items. compute it once into a small table (and ANALYZE it, so the planner knows what's in it), so every query below is only about the top-n part:
CREATE TABLE product_sales AS
SELECT p.id, p.name, p.category, sum(oi.qty)::int AS units
FROM products AS p
JOIN order_items AS oi ON oi.product_id = p.id
GROUP BY p.id;
ANALYZE product_sales;
SELECT category, name, units
FROM product_sales
ORDER BY units DESC, id
LIMIT 3;| categorytext | nametext | unitsint4 |
|---|---|---|
| kitchen | chef's knife | 3476 |
| kitchen | cast iron pan | 1386 |
| books | the art of sql | 1046 |
kitchen, kitchen, books. that's the shop's podium, not ten podiums.
three ways
row_number. number the rows inside each category, best first, and keep numbers 1 to 3. the numbering happens in a subquery because a window function can't go in WHERE (where windows run):
SELECT category, name, units, n
FROM (
SELECT *, row_number() OVER (PARTITION BY category ORDER BY units DESC, id) AS n
FROM product_sales
) AS ranked
WHERE n <= 3
ORDER BY category, n
LIMIT 6;| categorytext | nametext | unitsint4 | nint8 |
|---|---|---|---|
| audio | studio headphones | 773 | 1 |
| audio | folding earbuds | 627 | 2 |
| audio | basic earbuds | 351 | 3 |
| bath | classic shower caddy | 379 | 1 |
| bath | small shower caddy | 298 | 2 |
| bath | mini bath mat | 232 | 3 |
LATERAL. list the categories, and for each one run the query you'd write for a single category. LATERAL is what lets the inner query see c.category (LATERAL joins):
SELECT c.category, s.name, s.units
FROM (SELECT DISTINCT category FROM product_sales) AS c
CROSS JOIN LATERAL (
SELECT id, name, units FROM product_sales AS s
WHERE s.category = c.category
ORDER BY units DESC, id
LIMIT 3
) AS s
ORDER BY c.category, s.units DESC, s.id
LIMIT 6;| categorytext | nametext | unitsint4 |
|---|---|---|
| audio | studio headphones | 773 |
| audio | folding earbuds | 627 |
| audio | basic earbuds | 351 |
| bath | classic shower caddy | 379 |
| bath | small shower caddy | 298 |
| bath | mini bath mat | 232 |
DISTINCT ON. postgres only. sort by the group, then by "best", and keep the first row of each group (DISTINCT ON). one row per group, full stop:
SELECT DISTINCT ON (category) category, name, units
FROM product_sales
ORDER BY category, units DESC, id;| categorytext | nametext | unitsint4 |
|---|---|---|
| audio | studio headphones | 773 |
| bath | classic shower caddy | 379 |
| books | the art of sql | 1046 |
| games | travel dice tower | 317 |
| garden | hose reel | 735 |
| kitchen | chef's knife | 3476 |
| office | paper clips, free sample | 968 |
| outdoor | linen hammock | 514 |
| pets | cat tree | 621 |
| toys | linen yo-yo | 511 |
| null | wooden train | 665 |
every one of them ends its ORDER BY with id. if two products tie on units, "the best one" isn't one product until you say how to break the tie (ranking has the coin toss you get otherwise).
same question, three answers
ask all three for the top 1, so DISTINCT ON can play too:
- 1SELECT category, name, units
- 2FROM (SELECT *, row_number() OVER (PARTITION BY category ORDER BY units DESC, id) AS n
- 3 FROM product_sales) AS ranked
- 4WHERE n = 1
- 5ORDER BY category;
| categorytext | nametext | unitsint4 |
|---|---|---|
| audio | studio headphones | 773 |
| bath | classic shower caddy | 379 |
| books | the art of sql | 1046 |
| games | travel dice tower | 317 |
| garden | hose reel | 735 |
| kitchen | chef's knife | 3476 |
| office | paper clips, free sample | 968 |
| outdoor | linen hammock | 514 |
| pets | cat tree | 621 |
| toys | linen yo-yo | 511 |
| null | wooden train | 665 |
row_number: number each category's products, keep number 1. the three products with no category are a partition of their own, so there's a NULL row.
s.category = c.category is never true when the category is NULL.SELECT c.category, s.name
FROM (SELECT DISTINCT category FROM product_sales) AS c
CROSS JOIN LATERAL (
SELECT name FROM product_sales AS s
WHERE s.category = c.category
ORDER BY units DESC, id LIMIT 1
) AS s;
-- 11 distinct categories, NULL includedSELECT c.category, s.name, s.units
FROM (SELECT DISTINCT category FROM product_sales) AS c
CROSS JOIN LATERAL (
SELECT name, units FROM product_sales AS s
WHERE s.category IS NOT DISTINCT FROM c.category
ORDER BY units DESC, id
LIMIT 1
) AS s
ORDER BY c.category NULLS FIRST
LIMIT 2;| categorytext | nametext | unitsint4 |
|---|---|---|
| null | wooden train | 665 |
| audio | studio headphones | 773 |
the wooden train is back. (NULL and three-valued logic is why = couldn't find it.)
the plans
the answers match. the work doesn't. here's how postgres runs each one, read bottom-up:
- Subquery Scan on rankedFilter: (ranked.n = 1)
- ↑WindowAggWindow: w1 AS (PARTITION BY product_sales.category ORDER BY product_sales.units, product_sales.id ROWS UNBOUNDED PRECEDING)Run Condition: (row_number() OVER w1 <= 1)
- ↑SortSort Key: product_sales.category, product_sales.units DESC, product_sales.id
- ↑Seq Scan on product_sales
one sort by category and units, a WindowAgg that stops numbering each category after 1 (the run condition), and a filter on top.
- SortSort Key: product_sales.category
- ↑Nested Loop
- ↑HashAggregateGroup Key: product_sales.category
- ↑Seq Scan on product_sales
- ↑Limit
- ↑SortSort Key: s.units DESC, s.id
- ↑Seq Scan on product_sales sFilter: (category = product_sales.category)
a nested loop: the distinct categories outside, and inside, once per category, a scan of the whole table, a sort and a limit.
- Unique
- ↑SortSort Key: category, units DESC, id
- ↑Seq Scan on product_sales
one sort, then Unique keeps the first row of each category. the smallest plan of the three.
- row_number: Sort → WindowAgg → filter. the WindowAgg carries a
Run Condition: row_number only goes up within a category, so once it passes n postgres stops computing it for the rest of that category (one of the window speedups in postgres 15). the rows still go by; every row is read and sorted. - DISTINCT ON: Sort → Unique. the least machinery, and only for n = 1.
- LATERAL: a nested loop. outside, the 11 categories. inside, for each one, a scan, a sort, a limit. with no index that's 11 full scans of the table, which is fine for 199 rows and silly for 20 million.
and that's where the order flips. give LATERAL an index that matches its inner query, and each category becomes a short walk down the index that stops after n entries:
CREATE INDEX ON product_sales (category, units DESC, id);
EXPLAIN (COSTS OFF)
SELECT c.category, s.name, s.units
FROM (SELECT DISTINCT category FROM product_sales) AS c
CROSS JOIN LATERAL (
SELECT name, units FROM product_sales AS s
WHERE s.category = c.category
ORDER BY units DESC, id
LIMIT 3
) AS s
ORDER BY c.category;Limit over an Index Scan: no sort, no full scan per category. on a big table with few groups and a small n, that's the fastest of the three by far. row_number has to read everything regardless (an index can save its sort, not its scan). the operators themselves are nested loops, sorting and indexes for ORDER BY and LIMIT.
| row_number | LATERAL | DISTINCT ON | |
|---|---|---|---|
| n | any | any | 1 |
| reads | every row | n per group, with the right index | every row |
| NULL group | kept | dropped with = | kept |
| ties at the cut | rank() instead | FETCH FIRST n ROWS WITH TIES | no |
| standard SQL | yes | yes | postgres only |
keylines
- LIMIT cuts the whole result. "top n per group" needs a cut per group.
- row_number in a subquery: any n, one sorted pass over everything.
- LATERAL ... ORDER BY ... LIMIT n: one small query per group, fast with a matching index.
- DISTINCT ON: postgres only, n = 1, the smallest plan.
- end every ORDER BY with a key, and watch NULL group keys with
=.