MySQL: DENSE_RANK() reference
10 September 2023 (Updated 24 September 2023)
On this page
In a nutshell
The DENSE_RANK()
window function assigns a unique rank to each district row within a result set.
Example
Given this students
table:
name | score |
---|---|
Alice | 90 |
Bob | 85 |
Charlie | 85 |
David | 80 |
This query:
SELECT
name,
score,
DENSE_RANK() OVER (ORDER BY score DESC) as `rank`
FROM students;
Will produce this result:
name | score | rank |
---|---|---|
Alice | 90 | 1 |
Bob | 85 | 2 |
Charlie | 85 | 2 |
David | 80 | 3 |
The order of ranking is determined by the ORDER BY
cause within the DENSE_RANK()
function.
Other notes
- Unlike
RANK()
,DENSE_RANK()
will give duplicate rows the same rank and not skip any rankings.
Tagged:
MySQL
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment