SQL how-to
How to get the top N rows per group in SQL
Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)
Short answer
Number the rows inside each group with ROW_NUMBER() OVER (PARTITION BY species ORDER BY weight_kg DESC) in a subquery or CTE, then keep the rows numbered N or less. Use RANK() instead when tied rows should all make the cut.
The task: Get the top N rows within each group, for example the two heaviest pets of each species.
The two heaviest pets of each species
SELECT species, name, weight_kg
FROM (SELECT species, name, weight_kg,
ROW_NUMBER() OVER (PARTITION BY species ORDER BY weight_kg DESC) AS rn
FROM pets) ranked
WHERE rn <= 2
ORDER BY species, rn;Result (PostgreSQL and SQLite, identical): 8 rows
| species | name | weight_kg |
|---|---|---|
| bird | Ziggy | 0.1 |
| bird | Kiwi | 0.1 |
| cat | Socks | 7.4 |
| cat | Pumpkin | 5.2 |
| dog | Bruno | 30.1 |
| dog | Maple | 27.3 |
| rabbit | Juniper | 3.4 |
| rabbit | Clover | 2.1 |
Try it: PostgreSQL playground · SQLite playground
How it works
- 1
PARTITION BY speciesRestart the numbering for each species.
- 2
ORDER BY weight_kg DESCHeaviest first, so number 1 is the heaviest of its species.
- 3
FROM (…) rankedThe numbering must exist before you can filter on it, so it goes in a subquery (or CTE).
- 4
WHERE rn <= 2The top two of each group.
More examples
The same with a CTE
Reads top to bottom: rank first, then filter.
WITH ranked AS (
SELECT species, name, weight_kg,
ROW_NUMBER() OVER (PARTITION BY species ORDER BY weight_kg DESC) AS rn
FROM pets
)
SELECT species, name, weight_kg
FROM ranked
WHERE rn <= 2
ORDER BY species, rn;Result (PostgreSQL and SQLite, identical): 8 rows
| species | name | weight_kg |
|---|---|---|
| bird | Ziggy | 0.1 |
| bird | Kiwi | 0.1 |
| cat | Socks | 7.4 |
| cat | Pumpkin | 5.2 |
| dog | Bruno | 30.1 |
| dog | Maple | 27.3 |
| rabbit | Juniper | 3.4 |
| rabbit | Clover | 2.1 |
Try it: PostgreSQL playground · SQLite playground
RANK keeps ties
The top customer per city by number of orders. Where two customers tie, RANK keeps both; ROW_NUMBER would keep one at random.
SELECT city, name, orders
FROM (SELECT c.city, c.name, COUNT(o.id) AS orders,
RANK() OVER (PARTITION BY c.city ORDER BY COUNT(o.id) DESC) AS r
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.city, c.name) ranked
WHERE r = 1
ORDER BY city, name;Result (PostgreSQL and SQLite, identical): 5 rows
| city | name | orders |
|---|---|---|
| Austin | Maya Ortiz | 4 |
| Boston | Sam Okafor | 2 |
| Boston | Tomás Herrera | 2 |
| Chicago | Marcus Bell | 2 |
| Denver | Jonah Reed | 3 |
Try it: PostgreSQL playground · SQLite playground
Variations
Bottom N instead
Flip the order: ORDER BY weight_kg ASC gives the lightest.
Top N overall, not per group
No window needed: ORDER BY weight_kg DESC LIMIT 2.
Common mistakes
GROUP BY specieswithMAX(weight_kg): you get the top weight, but not which pet it belongs to.Filtering
WHERE ROW_NUMBER() … <= 2directly: window functions aren't allowed in WHERE.Expecting
ROW_NUMBERto keep ties: it never does. UseRANKorDENSE_RANK.
PostgreSQL and SQLite
Everything on this page works the same in PostgreSQL and SQLite: each example above was run on both, and the results match.
Official documentation
Go deeper
- Guide: SQL window functions
- Practice: SQL window functions practice: 8 exercises with answers
- Lesson: Ranking with OVER (Pro)
Make it stick in five minutes a day
“Ranking with OVER” teaches this step by step on a real database, with instant feedback. Part of sqlstreak Pro; the first lessons are free.