ROW_NUMBER vs RANK vs DENSE_RANK in SQL (The Complete Interview Guide)
If youβre preparing for SQL interviews or working on analytics and data engineering problems, you will encounter this question:
π What is the difference between ROW_NUMBER(), RANK(), and DENSE_RANK()?
They all look similar, but each solves a different business problem. Letβs understand them clearly with examples.
π§ Problem Statement
Assume we have an employees table with the following salaries:
- 90,000
- 80,000
- 80,000
- 70,000
We want to assign a ranking based on salary (highest first).
π’ 1. ROW_NUMBER()
SELECT salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn
FROM employees;
π How ROW_NUMBER() behaves
- Assigns a unique number to every row
- Ignores duplicates completely
Result:
- 90,000 β 1
- 80,000 β 2
- 80,000 β 3
- 70,000 β 4
β Best when:
- You want unique rows
- You need pagination
- You want the top N rows without caring about ties
π 2. RANK()
SELECT salary,
RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees;
π How RANK() behaves
- Same values get the same rank
- Skips ranks after duplicates
Result:
- 90,000 β Rank 1
- 80,000 β Rank 2
- 80,000 β Rank 2
- 70,000 β Rank 4 β
β Best when:
- Rank gaps are important
- You are building competition-style leaderboards
π― 3. DENSE_RANK()
SELECT salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS drnk
FROM employees;
π How DENSE_RANK() behaves
- Same values get the same rank
- No gaps in ranking
Result:
- 90,000 β Rank 1
- 80,000 β Rank 2
- 80,000 β Rank 2
- 70,000 β Rank 3 β
β Best when:
- Solving Nth highest / lowest problems
- You want continuous ranking
π Side-by-Side Comparison (Interview Favorite)
| Function | Handles duplicates | Skips ranks | Use case |
|---|---|---|---|
| ROW_NUMBER() | β No | β No | Pagination, top-N rows |
| RANK() | β Yes | β Yes | Leaderboards |
| DENSE_RANK() | β Yes | β No | Nth highest salary |
π‘ Real Interview Tip
π Nth highest / lowest value?
Always think DENSE_RANK()
π Top N rows strictly?
Use ROW_NUMBER()
π Competition or leaderboard ranking?
Use RANK()
π¬ Interview Question for You
How would you find the top 2 salaries per department, considering duplicates?
(Hint: Window functions + partitioning π)
Comments (1)
Thanks for sharing
Leave a Comment