RANK vs DENSE_RANK vs ROW_NUMBER in SQL
Tie semantics decide — state them, don’t just name them
ROW_NUMBER assigns unique 1..N (ties broken arbitrarily — pagination). RANK gives ties the same number with gaps after (1,1,3 — leaderboards with skipped places). DENSE_RANK gives ties the same number with no gaps (1,1,2 — Nth-salary). Nth-highest wants DENSE_RANK; deterministic pagination wants ROW_NUMBER + id tiebreak.
ROW_NUMBER uniques
1..N with arbitrary tie-break (+ id for determinism). Pagination.
RANK gaps
Ties share, places skip (1,1,3). Leaderboard places.
DENSE_RANK packs
Ties share, no gaps (1,1,2). Nth-distinct salary.
PARTITION restarts
Per-group numbering; top-N per group via CTE + rn <= N outside.
1SELECT name, salary, RANK() OVER (ORDER BY salary DESC) AS rnk, DENSE_RANK() OVER (ORDER BY salary DESC) AS drnk FROM employees ORDER BY salary DESC LIMIT 3;
| name | salary | rnk | drnk |
|---|---|---|---|
| Cynthia | 91000 | 1 | 1 |
| Alice | 85000 | 2 | 2 |
| Farid | 73000 | 3 | 3 |
No ties in the top three, so all three functions agree here. Duplicate a salary and RANK would skip (1,1,3) while DENSE_RANK would not (1,1,2) — that divergence is the interview answer.
Three functions side by side
No ties here — all agree. Duplicate a pay to split them.
1SELECT name, salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn, RANK() OVER (ORDER BY salary DESC) AS rnk, DENSE_RANK() OVER (ORDER BY salary DESC) AS drnk FROM employees ORDER BY salary DESC LIMIT 3;
| name | salary | rn | rnk | drnk |
|---|---|---|---|---|
| Cynthia | 91000 | 1 | 1 | 1 |
| Alice | 85000 | 2 | 2 | 2 |
| Farid | 73000 | 3 | 3 | 3 |
Top-1 per department
Partition-rank-filter mantra.
1SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) t WHERE rn = 1;
| name | department | salary |
|---|---|---|
| Cynthia | Engineering | 91000 |
| Elena | Sales | 58000 |
| David | Marketing | 47000 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.