RANK() Function in MS SQL Server with Examples
July 7, 2025
The RANK()
function is one of the ranking functions in T-SQL used to assign a rank to each row within a partition of a result set. It is especially useful for analytics and reporting scenarios.
β Syntax
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.
- The next rank(s) are skipped based on the number of ties.
Example: Ranks: 1, 2, 2, 4, 5 (note how rank 3 is skipped)
π§ͺ 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: RANK() by Sales (No Partitioning)
SELECT
EmployeeName,
SalesAmount,
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 | 5 |
Note: Bob and Carol share rank 3. Rank 4 is skipped.
π Example 2: RANK() with PARTITION BY Region
SELECT
EmployeeName,
Region,
SalesAmount,
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 | 3 |
Dave | West | 1800 | 1 |
Eva | West | 1600 | 2 |
Note: Ranks restart within each region using PARTITION BY
.
π Difference Between RANK(), DENSE_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 RANK()
- When you want to allow ties and skip ranks appropriately.
- Useful for leaderboards, contests, or percentile grouping.
- Can be used with pagination or top-N filtering per category.
β Summary
RANK()
is useful for ordered results with possible ties.PARTITION BY
helps reset ranks across logical groups.- Be mindful of skipped rankings when values are tied.
In the above example, we have seen how to use RANK() Function in MS SQL Server.
I have an another post MS SQL Server String Related Functions where you will learn about different rank related functions of MS SQL Server.
Hope you have enjoyed the tutorial. If you want to get updated, like the facebook page http://www.facebook.com/LearningBigDataAnalyticsΒ and stay connected.