DENSE_RANK
Description
The DENSE_RANK
function is a window function used to calculate the continuous rank of the current row within a specified partition, starting from 1. When the values in the ORDER BY
clause are the same, the DENSE_RANK
function generates the same rank, but the rank numbers do not skip.
Syntax
Parameter Description
PARTITION_clause
(optional): Specifies the clause for partitioning, used to divide the dataset into different partitions. If no partition is specified, the ranking is applied to the entire dataset.ORDER_BY_clause
: Specifies the columns or expressions used for sorting the data.
Return Type
The return value type is bigint
.
Usage Example
- Basic Usage
In this example, we partition employees by department ID and sort by salary in descending order, calculating each employee's salary rank within their department.
- No partition ranking
In this example, we did not specify a partition, so the inventory ranking will be calculated for the entire product dataset, sorted in ascending order by inventory quantity.
- Multi-column Sorting
In this example, we first partition by exam subjects, then sort by exam scores in descending order. If the scores are the same, then sort by student names in ascending order to calculate each student's ranking in each subject exam.
Notes
- When the values in the
ORDER BY
clause are the same, theDENSE_RANK
function does not generate skipped rankings; the rankings will repeat. - Compared to the
RANK()
function, theDENSE_RANK()
function provides more compact rankings when dealing with the same values, whereas theRANK()
function will produce discontinuous rankings. - When using the
DENSE_RANK()
function, ensure that theORDER BY
clause correctly reflects the way you want to sort the data.