DENSE_RANK
DENSE_RANK is a function in SQL that is used to rank items in a specific order. Unlike the RANK function, DENSE_RANK does not skip any ranks once a duplicate rank is encountered. Essentially, it assigns a unique rank to every distinct row within the partition of a result set, leaving no gaps in ranking sequence.
DENSE_RANK() OVER ([PARTITION BY partition_expression] ORDER BY sort_expression [ASC | DESC])
Example
Output
Explanation
In the example, the DENSE_RANK()
function is applied to the salary column in the employees table, which ranks employees based on their salary in descending order. Employees with same salary get the same rank. Unlike RANK()
, DENSE_RANK()
does not skip rank in case of ties, hence the rank follows orderly as 1, 2, 2, 3, 4, not 1, 2, 2, 4, 5.
DENSE_RANK() OVER ([PARTITION BY column_1, column_2,…] [ORDER BY column_1, column_2,… [ASC | DESC]], …)
Example
Output
Explanation
In this example, DENSE_RANK
function is used to rank the salaries of the employees in descending order. Unlike RANK
, DENSE_RANK
does not skip any ranks if there are rank ties. You can see that both Bob and Amy get a rank of 1 for having the highest salary. John, though having the same salary twice, is assigned the next rank, 2, and not 3. Amy’s lower salary is assigned the following rank, 3.
DENSE_RANK() OVER ([Partition By value_expression] Order By sort_expression [ASC | DESC])
Example
Output
SalesPerson | Revenue | Rank |
---|---|---|
John | 10000 | 1 |
Anna | 8000 | 2 |
Mark | 8000 | 2 |
Emma | 6000 | 3 |
Output
Explanation
The provided SQL code assigns a rank for each employee within their department based on the salary. The DENSE_RANK()
function is used to assign the ranking, where employees with higher salary get lower rank number. If two or more employees have the same salary, they receive the same rank, and the next rank is not skipped. The ranking is reset for each department due to the PARTITION BY
clause.