MS SQL Server DENSE_RANK() Function with Examples

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.

Add a Comment