The functions ROW_NUMBER(), RANK(), and DENSE_RANK() are window functions in SQL Server (and other databases) that are used to assign a ranking or numbering to rows within a partition. While they seem similar, they have distinct behaviors.
ORDER BY
column(s).Syntax
Select ROW_NUMBER() OVER (PARTITION BY partition_column ORDER BY order_column)
Example
SELECT
EmployeeID,
Salary,
ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum
FROM Employees;
Result
EmployeeID | Salary | RowNum |
---|---|---|
1 | 100000 | 1 |
2 | 80000 | 2 |
3 | 80000 | 3 |
4 | 60000 | 4 |
ORDER BY
column(s). Rows with duplicate values receive the same rank, and the next
rank is skipped.Syntax
Select RANK() OVER (PARTITION BY partition_column ORDER BY order_column)
Example
SELECT
EmployeeID,
Salary,
RANK() OVER (ORDER BY Salary DESC) AS Rank
FROM Employees;
Result
EmployeeID | Salary | Rank |
---|---|---|
1 | 100000 | 1 |
2 | 80000 | 2 |
3 | 80000 | 2 |
4 | 60000 | 4 |
RANK()
, but does not skip ranks for duplicate
values.Syntax
Syntax
Select DENSE_RANK() OVER (PARTITION BY partition_column ORDER BY order_column)
Example
SELECT
EmployeeID,
Salary,
DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRank
FROM Employees;
Result
EmployeeID | Salary | DenseRank |
---|---|---|
1 | 100000 | 1 |
2 | 80000 | 2 |
3 | 80000 | 2 |
4 | 60000 | 3 |
Feature | ROW_NUMBER() | RANK() | DENSE_RANK() |
---|---|---|---|
Duplicate Handling | Assigns unique numbers to all rows. | Assigns the same rank to duplicates but skips ranks. | Assigns the same rank to duplicates without skipping ranks. |
Gaps in Sequence | No gaps. | Gaps for ties. | No gaps for ties. |
Uniqueness | Always unique. | May have duplicates. | May have duplicates. |