Learning navigation

Code with Animation

Ranking & Running Totals

Rank rows with row_number, rank and dense_rank, handle ties and NULL, and build running totals that you can trust.

SQL7 min readConcept 28 of 44

Order inside the window

Add ORDER BY inside OVER (...) and the window has an order. That unlocks ranking functions and running totals.

row_number() counts rows 1, 2, 3 and never repeats. rank() gives tied rows the same number and then skips ahead. dense_rank() gives tied rows the same number and does not skip. Tied rows are called peers.

Leaderboards and progress

"Who are the top two in each team?", "What is the total so far each day?" and "How much did it change since yesterday?" are all window questions. They are hard with plain GROUP BY and short with window functions.

Ties, NULLs and running totals

SELECT name, points,
       row_number() OVER (ORDER BY points DESC NULLS LAST) AS rn,
       rank()       OVER (ORDER BY points DESC NULLS LAST) AS rk,
       dense_rank() OVER (ORDER BY points DESC NULLS LAST) AS dr
FROM players;

Dara and Fay both have 24 points. rank gives both 3 and the next player (17) gets 5. dense_rank gives both 3 and the next gets 4. row_number gives them 3 and 4.

A running total uses an aggregate with ORDER BY: sum(amount) OVER (ORDER BY day). With the default frame, rows that tie on day count as one step, so two rows on day 2 both show 100. Write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to add one row at a time, which gives 80 and then 100.

lag(amount) looks one row back and lead(amount) one row forward. The first row has no previous row, so lag gives NULL.

Rank players, total sales

In Ranking, toggle NULLS LAST and Top 2 per team. In Running total, compare the default frame with the ROWS frame on the tied day.

SELECT name, points, row_number() OVER (ORDER BY points DESC, id) AS row_number, rank() OVER (ORDER BY points DESC) AS rank, dense_rank() OVER (ORDER BY points DESC) AS dense_rank
FROM players
ORDER BY row_number;
Result (8 rows)
nametextpointsintegerrow_numberbigintrankbigintdense_rankbigint
ChenNULL111
EliNULL211
Gus40332
Asha31443
Dara24554
Fay24654
Ben17775
Hana17875

Without NULLS LAST, PostgreSQL puts NULL first when sorting DESC, so Chen and Eli rank 1 and the best scorer, Gus, is ranked 3. Add NULLS LAST to push missing values to the end.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Scores are 40, 24, 24, 17. What does `rank()` give for the last score (17), sorted DESC?
  2. 2`ORDER BY points DESC` is used inside a rank, and two players have NULL points. Where do they rank by default in PostgreSQL?
  3. 3`sum(amount) OVER (ORDER BY day)` runs over two rows that share day 2 (amounts 30 and 20), after a day 1 total of 50. What do both rows show?

Remember this

  • row_number never repeats. rank repeats on ties and leaves gaps. dense_rank repeats and has no gaps.
  • PostgreSQL sorts NULL first for DESC. Use NULLS LAST when missing values must not rank first.
  • A running total is an aggregate with ORDER BY inside OVER. The default frame includes tied rows, a ROWS frame adds one row at a time.
  • To keep the top N, rank in a subquery and filter outside. lag and lead read the previous and next row.

Done with this concept?

Mark it complete to track your progress. No login needed.