ROW_NUMBER vs RANK vs DENSE_RANK
The three ranking functions look identical until there is a tie. See the difference in one query, then use PARTITION BY to rank inside each group.
ROW_NUMBER vs RANK vs DENSE_RANK
All three window functions number rows. The difference only shows up when there are ties — and ties are exactly what make them worth understanding.
The same query, three functions
Count tracks per genre, then number the genres from largest to smallest:
SELECT g.name AS genre,
COUNT(*) AS tracks,
ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC, g.name) AS row_num,
RANK() OVER (ORDER BY COUNT(*) DESC) AS rank,
DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) AS dense_rank
FROM genres g
JOIN tracks t ON t.genre_id = g.id
GROUP BY g.id, g.name
ORDER BY tracks DESC, genre;
The result has eight rows — and two ties:
| genre | tracks | row_num | rank | dense_rank |
|---|---|---|---|---|
| Rock | 11 | 1 | 1 | 1 |
| Soul | 9 | 2 | 2 | 2 |
| Folk | 8 | 3 | 3 | 3 |
| Electronic | 6 | 4 | 4 | 4 |
| Jazz | 6 | 5 | 4 | 4 |
| Bossa Nova | 3 | 6 | 6 | 5 |
| Classical | 3 | 7 | 6 | 5 |
| Hip-Hop | 3 | 8 | 6 | 5 |
ROW_NUMBER() gives every row a different number. RANK() gives tied rows the same number and then skips the next one (4, 4, 6). DENSE_RANK() gives tied rows the same number without skipping (4, 4, 5). The row_num order inside a tie is arbitrary unless you add a tiebreaker, which is why the query sorts by g.name there.
When ties matter
The choice depends on the question:
- “Give me exactly the top three.” Use
ROW_NUMBER()and filterWHERE row_num <= 3. You get three rows, even if the third one is tied with the fourth. - “Give me everyone tied for first.” Use
RANK()orDENSE_RANK()and filterWHERE rank = 1. You get every leader, no matter how many there are. - “How many distinct ranks are there?” Use
DENSE_RANK(); it never skips a number.
A leaderboard usually wants RANK(); pagination usually wants ROW_NUMBER().
PARTITION BY: rank inside each group
Without PARTITION BY, the window sees the whole result. With it, numbering restarts for every group:
SELECT g.name AS genre, t.title, t.duration_sec,
ROW_NUMBER() OVER (PARTITION BY g.id ORDER BY t.duration_sec DESC) AS longest_rank
FROM tracks t
JOIN genres g ON g.id = t.genre_id
WHERE g.name IN ('Rock', 'Jazz')
ORDER BY g.name, longest_rank
LIMIT 6;
Each genre gets its own 1, 2, 3… — perfect for “the longest track per genre”. This is the pattern behind most top-N-per-group questions, and it is the one interviewers ask for.
Keep exploring: the window functions chapter covers ROW_NUMBER, RANK, LAG, running totals and frames with seven graded exercises.