RANK
Description
The RANK()
function is used to calculate the rank of the current row within a specified partition. The ranking starts from 1 and is sorted based on the values in the ORDER BY
clause. If there are identical sorting values, the RANK()
function assigns the same rank to these rows and skips the next rank.
Syntax
Parameter Description
PARTITION BY
: Optional parameter used to partition the data. You can specify one or more column names to partition the data.ORDER BY
: Optional parameter used to specify the columns and the sorting order (ascending or descending).
Return Value
- The return value type is bigint.
- The return value may be non-continuous and may have duplicates. If there are identical
ORDER BY
values, the result is the same, representing the rank of the firstORDER BY
row.
Example
- Basic Usage
We can use the
RANK()
function to calculate the salary rank of each employee. - Partition Usage
If we want to calculate salary rankings based on employee grades, we can use the
PARTITION BY
clause. - Multi-column Sorting
If we need to sort based on two or more columns, we can specify these columns in the
ORDER BY
clause.
Notes
- The
RANK()
function may produce non-continuous rankings in the presence of identical sort values. - When using the
RANK()
function, ensure that the columns in theORDER BY
clause match the columns you wish to rank by.