Top-N Records Per Category / Group
Return the top N items in each category with ranking windows.
In plain words
Number the rows inside each group from best to worst, then keep numbers 1 to N.
Think of it like…
Picking the top 3 students from every class for a quiz team: rank students within each class separately, then take the first three from each list.
Where you’ve seen it
An e-commerce home page shows the 4 best-selling products in each category. One query ranks products by units sold PARTITION BY category_id and keeps rn <= 4.
Words you’ll hear
- Group / partition
- The category the top-N restarts for.
- N
- How many rows to keep per group.
- LATERAL
- A join that runs a subquery, with its own LIMIT, once per row of the outer table.
- Tiebreaker
- An extra ORDER BY column that makes the result deterministic.
Visual diagram
Theory & example queries
The window-function solution
Rank inside each group, then filter. ROW_NUMBER returns exactly N rows per group; switch to RANK or DENSE_RANK if every row tied at position N should be included.
This works in PostgreSQL, MySQL 8+, SQL Server, Oracle, BigQuery and Snowflake. On old MySQL (5.7) without window functions you'd need a correlated subquery that counts how many rows beat each row.
WITH ranked AS ( SELECT category_id, product_id, units_sold, ROW_NUMBER() OVER ( PARTITION BY category_id ORDER BY units_sold DESC, product_id ) AS rn FROM product_sales )SELECT *FROM rankedWHERE rn <= 3;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Top three products per category4 sample rows
| category_id | product_id | units_sold | rn |
|---|---|---|---|
| 10 | 101 | 820 | 1 |
| 10 | 118 | 610 | 2 |
| 20 | 204 | 540 | 1 |
| 20 | 219 | 470 | 2 |
Note: Rows are representative; each category contributes at most three rows and ties are broken by product_id.
Key takeaway: Partition by the group, order by the metric, keep rn <= N.
Making it fast on big tables
The window version reads and sorts every row, then throws most of them away. With millions of rows and a few hundred groups, a LATERAL join can be much faster: for each category it fetches only the top N rows using an index on (category_id, units_sold DESC).
Always state the tie rule in your answer. "Top 3" with a tie at position 3 is ambiguous, so ask whether the interviewer wants exactly 3 rows (ROW_NUMBER) or everyone who tied (RANK).
SELECT c.id, p.*FROM categories c CROSS JOIN LATERAL ( SELECT product_id, units_sold FROM product_sales s WHERE s.category_id = c.id ORDER BY units_sold DESC LIMIT 3 ) p;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Top products returned by LATERAL3 sample rows
| category_id | product_id | units_sold |
|---|---|---|
| 10 | 101 | 820 |
| 10 | 118 | 610 |
| 20 | 204 | 540 |
Note: Representative output for categories 10 and 20; categories with no matching products are omitted by CROSS JOIN LATERAL.
Key takeaway: The window version is simple; LATERAL with an index is fast for few groups over huge tables.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Identify the group, metric and N
Translate the question: the group is category, the metric is units sold (higher is better), N is 3. Ask how ties at the cut-off should behave.
group · metric · N · ties
When to use it & trade-offs
What it is
Top-N per group returns the best N rows within each category, such as the 3 best-selling products per category or the 5 latest orders per customer. The standard solution ranks rows with a window function partitioned by the group and keeps rank ≤ N.
Why it matters: It's the most common "medium" SQL interview problem and appears constantly in product analytics. Interviewers also use it to probe how you handle ties and what you'd do on a very large table.
When to reach for it
- Top products per category, top customers per region
- The latest N events per user for a timeline
- Leaderboards per team or per season
When to avoid or be careful
- ORDER BY … LIMIT N without partitioning, which gives the top N overall
- Ignoring ties when the question says "top 3" and values repeat
- Running the window version over hundreds of millions of rows without considering an index-based plan
Three ways to get top-N per group
Strengths: Portable, readable, and handles ties explicitly.
Watch out: Reads and sorts every row.
Strengths: Reads only N rows per group with the right index.
Watch out: PostgreSQL/Oracle syntax (CROSS APPLY in SQL Server), and you need a table of groups.
Strengths: Works on very old engines.
Watch out: Slow, roughly quadratic per group, and awkward with ties.
Interview signals & numbers to know
When this topic comes up
- “Top 3 per category”
- “Latest 5 orders per customer”
- “Highest-paid employee in each department”
- Leaderboard
- PARTITION BY
Benchmarks & rules of thumb
- ROW_NUMBER
- exactly N per group
- RANK / DENSE_RANK
- N or more with ties
- (group, metric)
- index for the fast version
Common mistakes & follow-ups
Common interview mistakes
- Using ORDER BY + LIMIT and getting the top N overall instead of per group.
- Filtering rn <= N in the same query that computes rn.
- Not asking how ties at position N should be handled.
Likely interviewer follow-ups
- How does your answer change if two products tie for third place?
- How would you make this fast on a 500-million-row table?
- How would you write it in MySQL 5.7, without window functions?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Top-N Records Per Category / Group with hands-on SQL practice and interview Q&A.