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:
- Get one row per thing you are ranking (often an aggregate in its own CTE).
- Add the ranking function.
PARTITION BYrestarts the count in each group.ORDER BYinsideOVERsets the order. - Filter on the rank in an outer query. You cannot put a window function in
WHERE, because windows run afterWHERE.
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
- Ties. Decide before you code: keep all tied rows (
rankordense_rank) or exactly N (row_numberwith a tie-breaker). If the prompt does not say, ask or state your assumption. - No tie-breaker in
row_number. With equal values, which row gets 1 can change between runs. Add a unique column to theORDER BY, such as the id. rankversusdense_rankfor "Nth highest". "Second highest salary" usually means the second distinct value, which isdense_rank() = 2. Withrank, two people tied at the top leave no rank 2.- Ranking before aggregating. Rank the grouped result, not the raw rows. Ranking order items by quantity gives the biggest single line, not the best-selling product.
- NULLs in the sort. In PostgreSQL, NULLs sort last in ascending and first in descending order, so a NULL measure can take rank 1 under
desc. Addnulls lastor filter them out. - Filtering the window in the same
SELECT.where rnk <= 3in the query that createsrnkis an error. Wrap it.
Variations
- Top N overall.
order by x desc limit n, orfetch first n rows with tieswhen ties must stay. - Percent rank and
NTILE.ntile(4)splits rows into quartiles,percent_rank()gives a relative position. - Bottom N. Flip the sort direction.
- Rank by two keys.
order by revenue desc, orders descinside the window. - Compare to the top. Divide each row by
max(x) over (partition by group)to show a share of the leader.
In other warehouses
- Snowflake, BigQuery and Databricks have
QUALIFY, which filters on a window function directly:select ... from t qualify row_number() over (partition by k order by d desc) = 1. No outer query needed. PostgreSQL, SQL Server and MySQL do not have it, so use the CTE form above. - SQL Server uses
SELECT TOP 3 WITH TIES ...to keep ties at the cutoff. - NULL order differs. PostgreSQL and Snowflake put NULLs last in ascending order. BigQuery and SQL Server put them first. Write
nulls lastwhere supported (not in SQL Server) or filter NULLs out.