SQL • LESSON 26

RANK() & DENSE_RANK()

Learn how RANK() and DENSE_RANK() handle ties when ranking rows.

🔴 Advanced⏱ 3 Minutes⭐ 450 XP
🤔 THE QUESTION

What happens when two employees have the same salary, and how can we rank them correctly?

💡 WHAT IS IT?

RANK() and DENSE_RANK() assign rankings to rows based on an ordered value. Both handle ties, but they number the following rows differently.

🎯 WHAT IS IT USED FOR?

They are commonly used for leaderboards, salary rankings, top-N analysis, competition rankings, and comparing records with tied values.

💻 EXAMPLE
SELECT name,
salary,
RANK() OVER (
  ORDER BY salary DESC
) AS rank,
DENSE_RANK() OVER (
  ORDER BY salary DESC
) AS dense_rank
FROM employees;

Mission Brief

Practice comparing RANK() and DENSE_RANK() while ranking employees by salary.

Objectives

  • SELECT
  • RANK()
  • DENSE_RANK()
  • OVER
  • ORDER BY