Skip to content

Ranking and top N

Rank rows with window functions, keep the top N overall or per group, and decide what happens on ties.

Practise: 24 questions

When you need it

"Top 3 products per category", "the highest-paid person in each department", "the second most recent order". Words that signal it: "top", "best", "highest", "Nth", "rank", "per group".

A plain ORDER BY ... LIMIT 3 works for the top 3 of the whole table. As soon as the question says "in each", you need a window function, because LIMIT cannot restart for every group.

The shape of the query

with ranked as (
  select ..., 
         rank() over (partition by <group> order by <measure> desc) as rnk
  from ...
)
select * from ranked where rnk <= 3;

Step by step:

  1. Get one row per thing you are ranking (often an aggregate in its own CTE).
  2. Add the ranking function. PARTITION BY restarts the count in each group. ORDER BY inside OVER sets the order.
  3. Filter on the rank in an outer query. You cannot put a window function in WHERE, because windows run after WHERE.
with units as (
  select p.category, p.product_name, sum(oi.quantity) as units_sold
  from order_items oi
  join orders o on o.order_id = oi.order_id
  join products p on p.product_id = oi.product_id
  where o.status = 'completed'
  group by p.category, p.product_name
), ranked as (
  select category, product_name, units_sold,
         dense_rank() over (partition by category order by units_sold desc) as rnk
  from units
)
select category, product_name, units_sold, rnk
from ranked
where rnk <= 2
order by category, rnk, product_name;

The three functions treat ties differently. Say you have scores 90, 90, 80:

function result
row_number() 1, 2, 3 (ties broken arbitrarily)
rank() 1, 1, 3
dense_rank() 1, 1, 2

For a single "latest row per key", row_number() is the usual tool because it returns exactly one row per group:

select employee_id, effective_on, salary
from (
  select employee_id, effective_on, salary,
         row_number() over (partition by employee_id order by effective_on desc) as rn
  from salary_changes
) t
where rn = 1
order by employee_id
limit 10;

Traps interviewers look for

Variations

In other warehouses

Practise ranking and top n