Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 93/ 160
05. Window Functions & Analytical SQL

Top-N Records Per Category / Group

Return the top N items in each category with ranking windows.

IntermediateTop-N · Per Category3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Top 3 products per categoryQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  ranked AS (3    SELECT4      category_id,5      product_id,6      units_sold,7      ROW_NUMBER() OVER (8        PARTITION BY9          category_id10        ORDER BY11          units_sold DESC,12          product_id13      ) AS rn14    FROM15      product_sales16  )17SELECT18  *19FROM20  ranked21WHERE22  rn <= 3;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/22
3OutputInspect the representative rows, affected-row count, plan, or command status.
Top three products per category4 sample rows
Top three products per category
category_idproduct_idunits_soldrn
101018201
101186102
202045401
202194702

Note: Rows are representative; each category contributes at most three rows and ties are broken by product_id.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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

LATERAL version (PostgreSQL; SQL Server uses CROSS APPLY)Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  c.id,3  p.*4FROM5  categories c6  CROSS JOIN LATERAL (7    SELECT8      product_id,9      units_sold10    FROM11      product_sales s12    WHERE13      s.category_id = c.id14    ORDER BY15      units_sold DESC16    LIMIT17      318  ) p;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/18
3OutputInspect the representative rows, affected-row count, plan, or command status.
Top products returned by LATERAL3 sample rows
Top products returned by LATERAL
category_idproduct_idunits_sold
10101820
10118610
20204540

Note: Representative output for categories 10 and 20; categories with no matching products are omitted by CROSS JOIN LATERAL.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: The window version is simple; LATERAL with an index is fast for few groups over huge tables.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Problem

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.

Focus at this step

group · metric · N · ties

What to watch at this step
Clarify
ties
Tip: use ← → to move between steps

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

Window function (ROW_NUMBER / RANK)
Best for: Most cases, and interview answers

Strengths: Portable, readable, and handles ties explicitly.

Watch out: Reads and sorts every row.

LATERAL join + LIMIT
Best for: Few groups, very large tables

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.

Correlated subquery count
Best for: Databases without window functions

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?
Interview tip: Clarify ties first, write the ROW_NUMBER CTE version, then mention LATERAL with an index as the scaling answer. That covers correctness, edge cases and performance in one go.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Deduplicating Tables Using ROW_NUMBER() OVER (PARTITION BY ...)
Next topic
Year-over-Year (YoY), Month-over-Month (MoM) & Day-over-Day Growth