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 πŸ˜‰)