MS SQL Server DENSE_RANK() Function with Examples
July 8, 2025
The DENSE_RANK()
function is a ranking function in SQL Server that assigns a rank to each row within a partition of a result set, like RANK()
, but without gaps in ranking when duplicate values are found.
โ Syntax
DENSE_RANK() OVER (
[PARTITION BY partition_expression]
ORDER BY sort_expression [ASC|DESC]
)
- PARTITION BY: (Optional) Divides the result set into partitions.
- ORDER BY: Defines the order of the rows for ranking.
๐ Key Characteristics
- Rows with equal values receive the same rank.
- No gaps are left in the ranking sequence.
Example: Ranks: 1, 2, 2, 3, 4 (compared to RANK() which would give: 1, 2, 2, 4, 5)
๐งช Example Table: Sales
EmployeeID | EmployeeName | Region | SalesAmount |
---|---|---|---|
101 | Alice | East | 1200 |
102 | Bob | East | 1500 |
103 | Carol | East | 1500 |
104 | Dave | West | 1800 |
105 | Eva | West | 1600 |
๐ Example 1: DENSE_RANK() by Sales (No Partitioning)
SELECT
EmployeeName,
SalesAmount,
DENSE_RANK() OVER (ORDER BY SalesAmount DESC) AS SalesRank
FROM Sales;
๐ฝ Output
EmployeeName | SalesAmount | SalesRank |
---|---|---|
Dave | 1800 | 1 |
Eva | 1600 | 2 |
Bob | 1500 | 3 |
Carol | 1500 | 3 |
Alice | 1200 | 4 |
Note: Bob and Carol share rank 3, but unlike RANK()
, the next rank is 4, not 5.
๐ Example 2: DENSE_RANK() with PARTITION BY Region
SELECT
EmployeeName,
Region,
SalesAmount,
DENSE_RANK() OVER (PARTITION BY Region ORDER BY SalesAmount DESC) AS RegionalRank
FROM Sales;
๐ฝ Output
EmployeeName | Region | SalesAmount | RegionalRank |
---|---|---|---|
Bob | East | 1500 | 1 |
Carol | East | 1500 | 1 |
Alice | East | 1200 | 2 |
Dave | West | 1800 | 1 |
Eva | West | 1600 | 2 |
Note: Ranks restart within each region using PARTITION BY
.
๐ Comparison with RANK() and ROW_NUMBER()
Function | Behavior on Ties | Gaps in Ranking? |
---|---|---|
RANK() | Same rank for ties | Yes |
DENSE_RANK() | Same rank for ties | No |
ROW_NUMBER() | Always unique | N/A |
๐ง When to Use DENSE_RANK()
- When you want to rank rows without gaps.
- Useful in statistical analysis or reporting where equal values need the same rank but continuity matters.
- Ideal for scoring systems, percentile groups, and ranking within categories.
โ Summary
DENSE_RANK()
is useful for ordered results with ties and no skipped ranks.PARTITION BY
resets ranks by group.- Great for leaderboards, sales competitions, and business reporting.