RankFunctions
RankFunctions
SQL provides powerful ranking functions to assign a rank or unique number to each row within a partition
of a result set.
The three commonly used functions are:
ROW_NUMBER()
RANK()
DENSE_RANK()
These functions are used with the OVER() clause, which defines how to order and partition the data.
1. ROW_NUMBER()
Assigns a unique sequential number to each row within a partition.
Starts at 1 for each partition.
No ties: Even if rows have the same value, they get different row numbers.
Syntax:
ROW_NUMBER() OVER (PARTITION BY column_name ORDER BY column_name)
2. RANK()
Assigns the same rank to tied rows.
Skips ranks for the next values (non-continuous).
Syntax:
3. DENSE_RANK()
Similar to RANK(), but does not skip ranks after ties.
Syntax:
Comparison Table
Handles Skips
Function Use Case
Ties Ranks
Query:
WITH RankedEmployees AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Dept ORDER BY Salary DESC) AS RowNum
FROM Employee
)
SELECT * FROM RankedEmployees
WHERE RowNum <= 2;
Output:
EmpID Dept Salary RowNum
1 HR 60000 1
2 HR 55000 2
3 IT 80000 1
5 IT 80000 2
WITH Duplicates AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY EmpID, Dept, Salary ORDER BY EmpID) AS RowNum
FROM Employee
)
SELECT * FROM Duplicates
WHERE RowNum > 1;
StudentID Marks
1 95
2 98
3 95
4 92
Query:
1 C1 100 1/1/2024
2 C1 150 1/5/2024
3 C2 200 1/3/2024
4 C2 180 1/1/2024
Query:
WITH Ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY TransDate DESC) AS rn
FROM Transactions
)
SELECT * FROM Ranked WHERE rn = 1;
Output:
2 C1 150 1/5/2024 1
3 C2 200 1/3/2024 1