Window functions: ranking and top N
GROUP BY squashes rows into one per group. A window function computes the same kind of answer but keeps every row. This lesson starts there and ends with the most asked SQL interview question: the top N rows in each group.
Foundations · SQL for data engineers · Silver · Window functions, lesson 1 of 3
On this page
Read first: GROUP BY and HAVING (skip if you know it)
In plain words first
Suppose you want each order next to its city's total. GROUP BY city gives you the totals, but only one row per city: the orders are gone. A window function computes the total over a group of rows (the "window") and writes it on every row of that group.
GROUP BY: one row per group
Window: every row stays
You turn an aggregateaggregate: A function that turns many rows into one value: count, sum, avg, min, max. With GROUP BY it gives one value per group. Learn more → into a window function by adding OVER (...) after it. PARTITION BY city says which rows belong together:
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
SELECT order_id, city, amount, sum(amount) OVER (PARTITION BY city) AS city_total FROM orders ORDER BY city, order_id
All three Delhi orders show 1580, all five Pune orders show 1980. From here, "what share of its city is this order?" is just amount / city_total.
The parts of OVER (...)
| Part | Means | If you leave it out |
|---|---|---|
| PARTITION BY city | Split the rows into groups; each group is computed on its own | The whole table is one group |
| ORDER BY amount DESC | The order of rows inside each group | No order: fine for sum, but ranking needs one |
| ROWS BETWEEN ... | Which rows around the current one to use (the frameframe: The rows around the current row that a window function uses, such as ROWS BETWEEN 2 PRECEDING AND CURRENT ROW. Learn more →) | A default; see the running totals lesson |
Window functions run after WHERE, GROUP BY and HAVING, just before ORDER BY. That is why you cannot use one inside WHERE, which comes up below.
Three ways to number rows
Ranking functions give each row a position inside its partition. They differ only when two rows tie. Pune has two orders of 540 and Delhi two of 650, so watch those rows:
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
SELECT order_id, city, amount, row_number() OVER (PARTITION BY city ORDER BY amount DESC, order_id) AS row_num, rank() OVER (PARTITION BY city ORDER BY amount DESC) AS rnk, dense_rank() OVER (PARTITION BY city ORDER BY amount DESC) AS dense FROM orders WHERE city IN ('Pune', 'Delhi') ORDER BY city, row_num
| Function | Pune amounts 540, 540, 420, 300, 180 | Use it when |
|---|---|---|
| ROW_NUMBER | 1, 2, 3, 4, 5 | You need exactly one row per position, such as one latest row per key. Ties are split arbitrarily, so add a tie-breaker. |
| RANK | 1, 1, 3, 4, 5 | Ties share a place and the next place is skipped, like a race: two winners, then third. |
| DENSE_RANK | 1, 1, 2, 3, 4 | Ties share a place and no number is skipped: "the top 2 distinct amounts". |
order_id, whenever you use ROW_NUMBER.Top N per group
"The two biggest orders in each city" is the classic interview question. The trick has two steps, because WHERE runs before window functions and so cannot filter on them directly:
- 1In a subquerysubquery: A query inside another query, in brackets: in FROM as a table, or in WHERE with IN or EXISTS. Learn more →, number the rows in each city with a ranking function.
- 2In the outer query, keep the rows whose number is small enough.
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
SELECT city, order_id, amount FROM ( SELECT order_id, city, amount, row_number() OVER (PARTITION BY city ORDER BY amount DESC, order_id) AS rn FROM orders ) WHERE rn <= 2 ORDER BY city, rn
Which ranking function you pick changes the answer when there are ties, so it is worth saying out loud in an interview. "Every order with the biggest amount in its city" wants DENSE_RANK (or RANK) = 1, which returns both 540 orders in Pune and both 650 orders in Delhi:
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
SELECT city, order_id, amount FROM ( SELECT order_id, city, amount, dense_rank() OVER (PARTITION BY city ORDER BY amount DESC) AS dr FROM orders ) WHERE dr = 1 ORDER BY city, order_id
QUALIFY, a WHERE for window functions: ... QUALIFY row_number() OVER (...) <= 2. Open-source Spark SQL does not, so the subquery is the form that works everywhere.The latest row per key
Deduplication is the same pattern with N = 1: number each customer's orders newest first and keep row 1. Pipelines use this constantly to keep the latest version of each record.
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
SELECT customer_id, order_date, order_id, amount FROM ( SELECT *, row_number() OVER ( PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC ) AS rn FROM orders ) WHERE rn = 1 ORDER BY customer_id
NTILE: buckets of equal size
ntile(4) splits the ordered rows into 4 groups as equal as possible, numbered 1 to 4: quartiles. With 10 rows the groups have 3, 3, 2 and 2 rows.
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
SELECT order_id, amount, ntile(4) OVER (ORDER BY amount DESC, order_id) AS quartile FROM orders ORDER BY amount DESC, order_id
Notice the two 540 orders land in different quartiles: NTILE cuts by row count, not by value.
Common mistakes
- Filtering a window function in WHERE — WHERE runs before windows are computed. Compute the rank in a subquery or CTE, then filter outside.
- ROW_NUMBER without a tie-breaker — Tied rows can swap between runs, so "the latest row" changes. End ORDER BY with a unique column.
- Picking the wrong ranking function — ROW_NUMBER drops tied rows from a top N; DENSE_RANK keeps them. Decide what the question means by "top 2" before you write it.
- Forgetting PARTITION BY — Without it the ranking runs over the whole table: one overall top 2 instead of a top 2 per city.
Key takeaways
- A window function computes over a group of rows but keeps every row; add OVER (...) to an aggregate.
- PARTITION BY picks the groups, ORDER BY the order inside each group.
- ROW_NUMBER is 1, 2, 3; RANK is 1, 1, 3; DENSE_RANK is 1, 1, 2.
- Top N per group: rank in a subquery, filter in the outer query.
- Give ROW_NUMBER a unique tie-breaker so the answer never changes between runs.
Interview prep
THE QUESTION
"Return the two highest-paid employees in each department."
SELECT * FROM (SELECT *, dense_rank() OVER (PARTITION BY dept ORDER BY salary DESC) AS r FROM employees) WHERE r <= 2. Then ask about ties: with DENSE_RANK, two people on the same salary both count and you may return more than two rows per department; ROW_NUMBER with a tie-breaker returns exactly two. The filter has to be outside, because WHERE runs before the window function.Avoid: ROW_NUMBER with no word about ties. It returns exactly two rows per department, but if two people share the second-highest salary one of them is dropped at random, and the interviewer asked the question to see whether you notice.
Follow-ups · answer out loud, then open
Follow-up"Why can you not put the window function in WHERE?"
Scenario"A table receives several versions of each customer record. Keep only the latest version per customer."
row_number() OVER (PARTITION BY customer_id ORDER BY updated_at DESC, ingest_id DESC) in a subquery, keep row 1. The second sort key matters: two versions with the same timestamp would otherwise be picked at random, so the pipeline could give different answers on a rerun.Trap"Does rank() OVER (ORDER BY salary DESC) ever skip numbers?"
Check yourself
4 questionsA table has 10 rows in 3 cities. How many rows does SELECT city, sum(amount) OVER (PARTITION BY city) FROM t return?
Show the answer
10. A window function keeps every input row.
Amounts 90, 90, 70. What does RANK() give, highest first?
Show the answer
1, 1, 3. Ties share a rank and the next rank is skipped.
And DENSE_RANK()?
Show the answer
1, 1, 2. Ties share a rank and no number is skipped.
Why does WHERE row_number() OVER (...) = 1 fail?
Show the answer
WHERE runs before window functions are computed. Compute the window in a subquery, then filter it outside.
Practise this
Problems that use this, graded on hidden tests
- Top Two Salary Levels per DepartmentWindow Functions Medium
- Latest Order per CustomerWindow Functions Medium
- Customer Spend Quartiles (NTILE)Window Functions Medium
Keep going
Up next · Window functions · lesson 2 of 3 · 6 min readLAG and LEAD
Compare each row with the previous or next one: changes, gaps between events and day-over-day growth.
Related lessons
Running totals and window framesSQL for data engineers · 6 min read
CTEs and subqueries
Previous: Self joins
Primary sources: Window functions · Ranking functions