skip to content

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.

category audio
1studio headphones2folding earbuds3basic earbuds
category bath
1classic shower caddy2small shower caddy3mini bath mat
category books
1the art of sql2bamboo cookbook3mini notebook
category games
1travel dice tower2bamboo board game3retro go board
category garden
1hose reel2spare trowel3bamboo watering can
category kitchen
1chef's knife2cast iron pan3large whisk
category office
1paper clips, free sample2heavy stapler3folding desk lamp
category outdoor
1linen hammock2cotton lantern3travel lantern
category pets
1cat tree2pro leash3folding brush
category toys
1linen yo-yo2small puzzle3smart yo-yo
category null
1wooden train2smart stapler3large lantern

real output, postgres 18.6 (PGlite 0.5.12) · top-n-per-group
the answer we're after: the three best-selling products in every category, by units sold. eleven podiums, because three products have no category, and NULL makes a group of its own.

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:

sqldb=shop · session sales
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;
output, from postgres 18.6
#1 · SELECT 199
#2 · ANALYZE
#3 · SELECT 3
categorytextnametextunitsint4
kitchenchef's knife3476
kitchencast iron pan1386
booksthe art of sql1046
(3 rows)

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):

sqldb=shop · session sales
continues session sales (1 earlier block run first)
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;
output, from postgres 18.6
SELECT 6
categorytextnametextunitsint4nint8
audiostudio headphones7731
audiofolding earbuds6272
audiobasic earbuds3513
bathclassic shower caddy3791
bathsmall shower caddy2982
bathmini bath mat2323
(6 rows)

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):

sqldb=shop · session sales
continues session sales (2 earlier blocks run first)
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;
output, from postgres 18.6
SELECT 6
categorytextnametextunitsint4
audiostudio headphones773
audiofolding earbuds627
audiobasic earbuds351
bathclassic shower caddy379
bathsmall shower caddy298
bathmini bath mat232
(6 rows)

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:

sqldb=shop · session sales
continues session sales (3 earlier blocks run first)
SELECT DISTINCT ON (category) category, name, units
FROM product_sales
ORDER BY category, units DESC, id;
output, from postgres 18.6
SELECT 11
categorytextnametextunitsint4
audiostudio headphones773
bathclassic shower caddy379
booksthe art of sql1046
gamestravel dice tower317
gardenhose reel735
kitchenchef's knife3476
officepaper clips, free sample968
outdoorlinen hammock514
petscat tree621
toyslinen yo-yo511
nullwooden train665
(11 rows)

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:

method =
query.sql
  1. 1SELECT category, name, units
  2. 2FROM (SELECT *, row_number() OVER (PARTITION BY category ORDER BY units DESC, id) AS n
  3. 3 FROM product_sales) AS ranked
  4. 4WHERE n = 1
  5. 5ORDER BY category;
the result for row_number
categorytextnametextunitsint4
audiostudio headphones773
bathclassic shower caddy379
booksthe art of sql1046
gamestravel dice tower317
gardenhose reel735
kitchenchef's knife3476
officepaper clips, free sample968
outdoorlinen hammock514
petscat tree621
toyslinen yo-yo511
nullwooden train665
(11 rows)

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.

real output, postgres 18.6 (PGlite 0.5.12) · top-n-per-group
switch the method. row_number and DISTINCT ON return eleven rows, with the uncategorised wooden train last. LATERAL returns ten: its s.category = c.category is never true when the category is NULL.
predict the output
sql
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 included
sqldb=shop · session sales
continues session sales (4 earlier blocks run first)
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 IS NOT DISTINCT FROM c.category
  ORDER BY units DESC, id
  LIMIT 1
) AS s
ORDER BY c.category NULLS FIRST
LIMIT 2;
output, from postgres 18.6
SELECT 2
categorytextnametextunitsint4
nullwooden train665
audiostudio headphones773
(2 rows)

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:

row_number11 rows
  1. Subquery Scan on ranked
    Filter: (ranked.n = 1)
  2. ↑WindowAgg
    Window: 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)
  3. ↑Sort
    Sort Key: product_sales.category, product_sales.units DESC, product_sales.id
  4. ↑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.

LATERAL10 rows
  1. Sort
    Sort Key: product_sales.category
  2. ↑Nested Loop
  3. ↑HashAggregate
    Group Key: product_sales.category
  4. ↑Seq Scan on product_sales
  5. ↑Limit
  6. ↑Sort
    Sort Key: s.units DESC, s.id
  7. ↑Seq Scan on product_sales s
    Filter: (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.

DISTINCT ON11 rows
  1. Unique
  2. ↑Sort
    Sort Key: category, units DESC, id
  3. ↑Seq Scan on product_sales

one sort, then Unique keeps the first row of each category. the smallest plan of the three.

real output, postgres 18.6 (PGlite 0.5.12) · top-n-per-group
EXPLAIN (COSTS OFF) of the three top-1 queries. row_number and DISTINCT ON both make one sorted pass over the table. LATERAL scans the table once to find the categories, and then once more per category, inside the nested loop.
  • 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:

sqldb=shop · session sales
continues session sales (5 earlier blocks run first)
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;
output, from postgres 18.6
#1 · CREATE INDEX
#2 · EXPLAIN
Sort Sort Key: product_sales.category -> Nested Loop -> HashAggregate Group Key: product_sales.category -> Seq Scan on product_sales -> Limit -> Index Scan using product_sales_category_units_id_idx on product_sales s Index Cond: (category = product_sales.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_numberLATERALDISTINCT ON
nanyany1
readsevery rown per group, with the right indexevery row
NULL groupkeptdropped with =kept
ties at the cutrank() insteadFETCH FIRST n ROWS WITH TIESno
standard SQLyesyespostgres 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 =.