Window functions
RANK and DENSE_RANK
Compare gap-producing and gap-free ranks when values tie.
Lesson 60 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Advanced
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Compare gap-producing and gap-free ranks when values tie.
Run the example
sql
SELECT EmployeeID, AnnualSalary,
RANK() OVER (ORDER BY AnnualSalary DESC) AS SalaryRank,
DENSE_RANK() OVER (ORDER BY AnnualSalary DESC) AS DenseSalaryRank
FROM dbo.Employees
ORDER BY AnnualSalary DESC, EmployeeID;Read it step by step
- Both functions assign the same rank to equal salary values.
- RANK skips following numbers after a tie; DENSE_RANK does not.
- EmployeeID only breaks ties in final display, not inside either ranking window.
Check the result
| EmployeeID | AnnualSalary | SalaryRank | DenseSalaryRank |
|---|---|---|---|
| 9 | 66000.00 | 1 | 1 |
| 5 | 64000.00 | 2 | 2 |
| 1 | 62000.00 | 3 | 3 |
| 8 | 52000.00 | 4 | 4 |
| 12 | 50000.00 | 5 | 5 |
| 10 | 43000.00 | 6 | 6 |
| 3 | 42000.00 | 7 | 7 |
| 6 | 41000.00 | 8 | 8 |
| 11 | 41000.00 | 8 | 8 |
| 7 | 40000.00 | 10 | 9 |
| 2 | 39000.00 | 11 | 10 |
| 4 | 37000.00 | 12 | 11 |
Inspect equal salaries to see where the two rank columns diverge.
Practice
Rank the salaries of Employees 6, 7, 10, and 11 with both functions. Where does a gap appear?
Check your answer and expected result
Reveal answer
sql
SELECT EmployeeID, AnnualSalary,
RANK() OVER (ORDER BY AnnualSalary DESC) AS SalaryRank,
DENSE_RANK() OVER (ORDER BY AnnualSalary DESC) AS DenseSalaryRank
FROM dbo.Employees
WHERE EmployeeID IN (6, 7, 10, 11)
ORDER BY AnnualSalary DESC, EmployeeID;| EmployeeID | AnnualSalary | SalaryRank | DenseSalaryRank |
|---|---|---|---|
| 10 | 43000.00 | 1 | 1 |
| 6 | 41000.00 | 2 | 2 |
| 11 | 41000.00 | 2 | 2 |
| 7 | 40000.00 | 4 | 3 |
Employees 6 and 11 tie at 41,000. Employee 7 then receives RANK 4 but DENSE_RANK 3.
Your progress
Reveal the check answer or reach the end to complete this lesson.