Stop 08 · Window FunctionsTopics · 9/9

Top-N per Group Pattern

Part of the SQL Roadmap

In short

"Top 3 products in each category", "latest 2 orders per customer", "best-rated restaurant per city". This one pattern shows up in reports and interviews again and again, and it always has the same shape.

Finding the top N rows within each group, such as the three best-selling products per category, is a classic pattern: number the rows with ROW_NUMBER or RANK partitioned by group, then filter in an outer query or CTE.

The jaadu hangs three small medals on hooks outside each of several coaching centre doorways along a busy street.

Think of it like this

Toppers banners at every coaching branch

A coaching institute in Kota has branches across the city. Each branch prints its own banner with its top 3 students. Branch A's toppers never compete with Branch B's. That's Top-N per group: rank inside each branch, then keep only the first three of each.

Watch it happen

The three-step Top-N recipe

Products
PARTITION BY
ROW_NUMBER
rn <= 3
Result

1/5Start with every product and its revenue: 60 products across 5 categories.

The big ideas

What you need to know

LIMIT is global

ORDER BY revenue DESC LIMIT 3 gives the top 3 overall, not per group. You need a window function.

Rank, then filter

Number the rows in a CTE or subquery, then filter on the number outside. It's always two layers.

Pick your tie rule

ROW_NUMBER returns exactly N per group. RANK or DENSE_RANK can return more when there are ties.

PostgreSQL shortcuts

For N = 1, DISTINCT ON (category) is short and fast. For large N, a LATERAL join with LIMIT also works.

See it in code

Walk through the code

sql
1WITH ranked AS (2  SELECT3    category,4    product_name,5    revenue,6    ROW_NUMBER() OVER (7      PARTITION BY category8      ORDER BY revenue DESC, product_name9    ) AS rn10  FROM product_sales11)12SELECT category, rn, product_name, revenue13FROM ranked14WHERE rn <= 315ORDER BY category, rn;

1/4Each category gets its own numbering, highest revenue first. product_name breaks ties.

Top 3 products by revenue in each category. The same query runs on PostgreSQL, MySQL 8+ and SQL Server.

Save yourself the pain

Common mistakes

Oops

Writing ORDER BY revenue DESC LIMIT 3 and calling it 'top 3 per category'.

Do this instead

That's the top 3 overall. Partition by category with a window function and filter on the row number.

Oops

Putting rn <= 3 in the WHERE of the same SELECT that computes rn.

Do this instead

WHERE runs before the window function. Filter in an outer query over a CTE or subquery.

Your mission

Latest two orders per customer

~20 min

Quick check

Five categories, and you want the top 2 products in each with ROW_NUMBER. How many rows come back at most?

Go deeper

  1. 1Find the top 3 products by revenue in each category.
  2. 2Decide whether ties should be included and choose ROW_NUMBER, RANK or DENSE_RANK to match.
  3. 3Remember window results cannot be filtered in WHERE of the same query; wrap them in a CTE.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge