RANK() and DENSE_RANK() vs Row_Number() function in sql

Let’s understand the difference between RANK(), DENSE_RANK(), and ROW_NUMBER() functions in SQL with an example.

Consider the following Employees table:

EmployeeIDNameSalary
1John5000
2Alice5000
3Bob6000
4David7000
5Ethan8000
6Frank8000
7Grace9000

Now, let’s apply the RANK(), DENSE_RANK(), and ROW_NUMBER() functions on the Salary column:

SELECT 
    EmployeeID, 
    Name, 
    Salary,
    RANK() OVER (ORDER BY Salary) as Rank,
    DENSE_RANK() OVER (ORDER BY Salary) as Dense_Rank,
    ROW_NUMBER() OVER (ORDER BY Salary) as Row_Number
FROM Employees;

The output would be:

EmployeeIDNameSalaryRankDense_RankRow_Number
1John5000111
2Alice5000112
3Bob6000323
4David7000434
5Ethan8000545
6Frank8000546
7Grace9000757

Here’s how each function works:

  • RANK(): This function gives the same rank for equal values. Notice that both John and Alice have a rank of 1. The next rank, however, is 3 (not 2) because two rows have taken the first two ranks.
  • DENSE_RANK(): This function also gives the same rank for equal values, but unlike RANK(), it does not skip any rank. So, after John and Alice, Bob gets a rank of 2.
  • ROW_NUMBER(): This function simply gives a unique row number to each row irrespective of duplicates. So, even though John and Alice have the same salary, they get different row numbers.


Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form