Skip to content
Silver 7 min read · Windows 3 practice problems ↓

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

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

10 orders in 3 cities become 3 rows. You see the totals but lose the orders.

Window: every row stays

10 orders stay 10 rows. Each one gets an extra column computed from its group.

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:

Spark SQL · Each order with its city's total

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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 (...)

PartMeansIf you leave it out
PARTITION BY citySplit the rows into groups; each group is computed on its ownThe whole table is one group
ORDER BY amount DESCThe order of rows inside each groupNo 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:

Spark SQL · ROW_NUMBER, RANK and DENSE_RANK side by side

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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
FunctionPune amounts 540, 540, 420, 300, 180Use it when
ROW_NUMBER1, 2, 3, 4, 5You need exactly one row per position, such as one latest row per key. Ties are split arbitrarily, so add a tie-breaker.
RANK1, 1, 3, 4, 5Ties share a place and the next place is skipped, like a race: two winners, then third.
DENSE_RANK1, 1, 2, 3, 4Ties share a place and no number is skipped: "the top 2 distinct amounts".
Watch out: With ties, ROW_NUMBER without a tie-breaker can number 204 and 206 either way, and the answer may change between runs. Add a unique column at the end of ORDER BY, here 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:

  1. 1
    In 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.
  2. 2
    In the outer query, keep the rows whose number is small enough.
Spark SQL · Two biggest orders per city

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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:

Spark SQL · Every order tied for first place

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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
Tip: Some databases (Snowflake, BigQuery, Databricks SQL) have 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.

Spark SQL · Each customer's latest order

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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.

Spark SQL · Orders in spend quartiles

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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."

Rank inside each department in a subquery, then filter: 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?"
WHERE runs before window functions are computed (FROM, WHERE, GROUP BY, HAVING, then windows, then ORDER BY). The rank does not exist yet, so compute it in a subquery or CTE and filter in the outer query. Some engines add QUALIFY for this; open-source Spark SQL does not.
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?"
Yes: after a tie, RANK jumps (1, 1, 3). DENSE_RANK does not (1, 1, 2), and ROW_NUMBER never ties (1, 2, 3). "The second-highest salary" is DENSE_RANK = 2; RANK = 2 can return nothing at all.

Check yourself

4 questions

A 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

See all 4 problems →

Keep going

Up next · Window functions · lesson 2 of 3 · 6 min read
LAG and LEAD
Compare each row with the previous or next one: changes, gaps between events and day-over-day growth.

Related lessons

Previous: Self joins

Primary sources: Window functions · Ranking functions