MySQL DENSE_RANK Function

MySQL DENSE_RANK Function

MySQL DENSE_RANK Function

The DENSE_RANK() function in MySQL is used to assign a rank to each row within a partition of a result set. Unlike RANK(), it does not leave gaps in ranking when there are duplicate values.

1. What is DENSE_RANK in MySQL?

✅ Assigns a ranking to rows based on a specified order
No gaps between ranks, even for duplicate values
✅ Similar to RANK(), but more compact

🔹 Syntax:

DENSE_RANK() OVER (PARTITION BY column ORDER BY column)

2. Key Differences Between RANK() and DENSE_RANK()

FunctionHandles DuplicatesGaps in Ranking?
RANK()Same values get the same rank✅ Yes (skips ranks)
DENSE_RANK()Same values get the same rank❌ No gaps

Example Difference

IDNameScoreRANK()DENSE_RANK()
1Alice9011
2Bob8522
3Charlie8522
4David8043

DENSE_RANK() does not skip 3, unlike RANK(), which jumps from 2 → 4.

3. How to Use DENSE_RANK() in MySQL

Example: Ranking Students by Score

SELECT id, name, score, DENSE_RANK() OVER (ORDER BY score DESC) AS rank FROM students;

🔹 Results:

IDNameScoreRank
1Alice951
2Bob902
3Charlie902
4David853

4. Using DENSE_RANK() with PARTITION BY

You can group ranks by category using PARTITION BY.

Example: Ranking Employees by Department

SELECT id, name, department, salary, DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank FROM employees;

🔹 Results:

IDNameDepartmentSalaryRank
1AliceIT50001
2BobIT48002
3CharlieHR45001
4DavidHR42002

✅ Employees are ranked within their department.

5. When to Use DENSE_RANK()?

✅ When you don't want ranking gaps
✅ Useful for leaderboards, competitions, and report generation
✅ Ideal for ranking grouped data (e.g., sales by region)

6. Conclusion

  • DENSE_RANK() ranks rows without gaps.
  • It's useful for grouped rankings using PARTITION BY.
  • It differs from RANK(), which skips numbers when duplicates exist.

🚀 Use DENSE_RANK() for compact and sequential ranking in MySQL queries!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close