Skip to content
Codewilds

Lesson 29 of 30 · Advanced Queries

SQL Window Functions: ROW_NUMBER, RANK and Running Totals

hard30 XP3 min read

GROUP BY answers questions about groups, but it squashes each group into a single row. Often you want to keep every row and see it in context: who is the richest hero of each class, and how do the rewards add up? Window functions compute a value across a set of related rows, the window, and attach it to every row.

OVER: the window

SELECT name, class, gold,
       MAX(gold) OVER (PARTITION BY class) AS class_best
FROM heroes;

MAX(gold) is the aggregate you know, but OVER (…) turns it into a window function: all 15 heroes stay in the result, and each row shows the highest gold in its class. PARTITION BY class splits the rows into one window per class, like GROUP BY without collapsing them. An empty OVER () makes the whole table one window.

Numbering and ranking rows

Add ORDER BY inside OVER to order the rows of each window, then number them:

SELECT name, class, level,
       ROW_NUMBER() OVER (PARTITION BY class ORDER BY level DESC) AS pos
FROM heroes;

The highest-level hero of each class gets pos 1, the next one 2, and the numbering starts again in every class.

When values tie, the ranking functions differ. This query ranks heroes by their number of completed quests:

SELECT hero_id, COUNT(*) AS quests,
       ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) AS row_num,
       RANK() OVER (ORDER BY COUNT(*) DESC) AS rnk
FROM completions
GROUP BY hero_id;
quests heroes ROW_NUMBER() RANK()
4 1 1 1
3 4 2, 3, 4, 5 2 for all four
2 6 6 to 11 6 for all six

ROW_NUMBER() always counts 1, 2, 3 …, and puts tied rows in an arbitrary order. RANK() gives tied rows the same rank and then skips ahead, like a sports table. DENSE_RANK() doesn't skip: 1, 2, 2, 2, 2, 3. Window functions run after GROUP BY, which is why they can use COUNT(*).

Running totals

With ORDER BY in the window, SUM becomes a running total: the sum of every row up to the current one.

SELECT bought_on, quantity,
       SUM(quantity) OVER (ORDER BY bought_on) AS running_total
FROM purchases
WHERE hero_id = 3;
bought_on quantity running_total
2024-08-22 1 1
2024-09-29 6 7
2025-05-18 2 9

Common mistakes

  • Filtering on a window function in WHERE. WHERE pos = 1 fails with misuse of aliased window function pos, because WHERE runs before window functions are computed. Compute them in a CTE and filter in the outer query.
  • No ORDER BY in the window for ROW_NUMBER() or RANK(). The numbering is then arbitrary.
  • Ties in a running total. Rows with the same ORDER BY value get the same running total. Add a tie-breaker, as in ORDER BY bought_on, id.

Assignment

The quests table has the columns id, title, region, difficulty ('easy', 'medium' or 'hard') and reward. For every quest, show:

  • title, difficulty and reward
  • rank_in_tier: the quest's position within its difficulty by reward, best-paid first (1, 2, 3 …)
  • tier_total: a running total of the rewards within its difficulty, from the best-paid quest down. It's what a hero earns by doing this quest and every better-paid quest of the same difficulty.

Sort the result by difficulty (A to Z), then by rank_in_tier.

Premium lesson

Unlock the full Learn SQL course

  • All 30 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 7 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The SQL cheat sheet has every topic of Learn SQL on one page.

Lesson last updated on .

Write code ↓
SQL+30 XP

Lesson 29 is part of the full course. The first 7 lessons are free.

Premium lesson

Unlock the full Learn SQL course

  • All 30 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 7 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.