Returns the rank of the current row with gaps; same as row_number of its first peer.
Syntax
1rank()OVER([ PARTITION BY <expression>[, ...]]ORDER BY<expression>[, ...])
Arguments
rank takes no arguments.
Returns
Returns a bigint.
Considerations
rank depends on the ORDER BY clause of the window definition to determine the rank of each row. Without ORDER BY, all rows are peers and every row gets a rank of 1.
Rows that aren’t unique in the ORDER BY columns are peers and receive the same rank.
After a group of tied rows, the next rank skips ahead by the number of tied rows and leaves a gap. For example, two rows tied at rank 2 are followed by rank 4, not rank 3.
rank contrasts with dense_rank, which ranks without gaps, and with modified_rank, which also produces gaps but assigns the tied group the rank of its last peer instead of its first. For more information, see DENSE_RANK and MODIFIED_RANK.
For more information about the OVER clause and window frames, see Window Function Call Syntax. For more information about naming a window definition with a WINDOW clause, see SELECT.
Examples
Rank Rows Within a Partition
Rank employees by salary within each department.
1SELECT2 depname,3 rank()OVER(PARTITION BY depname ORDER BY salary DESC)AS rank,4 salary,5 empno6FROM empsalary7ORDER BY depname, rank;
The rank function produces a numerical rank for each unique ORDER BY value in the current row’s partition and uses the order defined by the ORDER BY clause. In the develop department, empno 10 and 11 tie for rank 2, so the next row, empno 9, receives rank 4 rather than rank 3.
Rank Rows Without Partitioning
Rank all rows in a table by salary without dividing them into partitions.
1SELECT empno, salary, rank()OVER(ORDER BY salary DESC)2FROM empsalary;
Omitting PARTITION BY treats all rows as a single partition, so the rank reflects each employee’s salary standing across the entire table.