All three function known as a window function in Microsoft SQL Server, the difference between rank(), dense_rank(), and row_number() comes when you have duplicate records in a columns where you want to apply ranking For example, if you are ranking employees by their salaries then what would be the rank of two employees of the same salaries? It depends on which ranking function you are using like row_number, rank, or dense_rank.
CREATE TABLE [dbo].[employee](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [nvarchar](50) NULL,
[age] [int] NULL,
[salary] [decimal](18, 0) NULL
)
SELECT *
FROM employee
ROW_NUMBER():- The row_number() function always generates a unique ranking even with duplicate records. As you can see below in query result.
SELECT *,
ROW_NUMBER() OVER (ORDER BY id) AS Ranking
FROM employee
RANK():- The rank() function will assign the same rank to the same values . But, the next different rank will not start from immediately next number but there will be a double increment like u can see in employee id 1 that is start from ranking 3 skip the ranking 2.
SELECT *,
RANK() OVER (ORDER BY salary ) AS Ranking
FROM employee
Dense_Rank():- The dense_rank function is similar to the rank() window function i.e. same values will be assigned the same rank, but the next different value will have a rank which is just one more than the previous rank.
SELECT *,
DENSE_RANK() OVER (ORDER BY salary ) AS Ranking
FROM employee