# Ranking & Running Totals

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

Subject: SQL | Lesson 28 of 44 | 7 min read
Interactive lesson: https://codewithanimation.in/sql/ranking-and-running-totals
Previous: [Window Functions](https://codewithanimation.in/sql/window-functions.md) | Next: [INSERT](https://codewithanimation.in/sql/insert-rows.md)

## 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

```sql
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.

## Common mistake: NULL order and top N

PostgreSQL sorts NULL first when you sort descending. `ORDER BY points DESC` makes Chen and Eli rank 1, ahead of the best scorer. Write `NULLS LAST` whenever missing values should not win.

A window function cannot appear in `WHERE`. To keep the top 2 per team, rank in a subquery, then filter outside: `SELECT * FROM (SELECT ..., row_number() OVER (PARTITION BY team ORDER BY points DESC NULLS LAST) AS rn FROM players) AS ranked WHERE rn <= 2`.

If two rows tie on the `ORDER BY` columns, `row_number` still gives them different numbers, and which one comes first is not guaranteed. Add a unique column such as `id` as a tie-breaker when the order must be stable.

## Tip: Choose the ranking by what a tie should do

Want every row numbered exactly once (for paging or picking one row)? `row_number`. Want ties to share a place with gaps, like a race? `rank`. Want places without gaps? `dense_rank`. For running totals, state the frame yourself when ties are possible.

## Try it: 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.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/ranking-and-running-totals

## Check yourself

### Question 1

Scores are 40, 24, 24, 17. What does `rank()` give for the last score (17), sorted DESC?

- A. 4
- B. 3
- C. 2

Correct answer: A

The two 24s share rank 2, and rank then skips to 4. dense_rank would continue with 3.

- Why not B: 3 is what dense_rank gives. rank skips a number after the tie.
- Why not C: The two 24s share rank 2, so 17 comes after both of them.

### Question 2

`ORDER BY points DESC` is used inside a rank, and two players have NULL points. Where do they rank by default in PostgreSQL?

- A. First, because NULL sorts first when descending
- B. Last, because NULL means nothing
- C. They are left out

Correct answer: A

NULL sorts as larger than any value, so it comes first in a descending order. Add NULLS LAST to avoid it.

- Why not B: That is the ASC behaviour. For DESC, PostgreSQL puts NULL first unless you write NULLS LAST.
- Why not C: Ranking does not remove rows. They are ranked like any other rows.

### Question 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?

- A. 100, because tied rows are in the same frame
- B. 80 and 100
- C. 30 and 20

Correct answer: A

With the default frame, the window runs through the last peer of the current row, so both day-2 rows include each other.

- Why not B: That is what a ROWS frame gives. The default frame includes all peers of the current row.
- Why not C: That would be the amounts alone. The window adds up from the start.

## 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.
