Row_Number() will generate a unique number for every row, even if one or more rows has the same value.
RANK() will assign the same number for the row which contains the same value and skips the next number.
DENSE_RANK () will assign the same number for the row which contains the same value without skipping the next number.
To understand the above example, here I have given a simple explanation.
The Salary values were unique until the 4th row, and all three functions return 4 on row four. The 5th salary column has the same salary as row four so it’s a tie. ROW_NUMBER function does not care; it continues to provide unique incrementing numbers. RANK and DENSE_RANK both return four again because both rows four and five are ranked the same.
Let's insert one more employee with the same salary. Employee Name is Tod and salary is 7000.
-
-
- INSERT INTO dbo.Employee
-
- VALUES ('Tod',7000)
-
- GO
Look at the rank function and see how many rows have the same value. Look at snippet 1 and snippet 2; you will get a clear vision that rank function has skipped 5 because only Warner and Elly have the same salary with 7000. Now snippet 2 has three employees, Warner, Elly, and Tod, with a salary of 7000. Hence rank function has skipped the numbers 5 and 6 and generated beginning from 7.
Dense_Rank function will assign the same rank for those rows which have the same values without the skipping next number.
I hope all three functions clear from above given example. If you have any query or question on raw_number(), Rank() or Dense_Rank() function feel free to write to me.
Thank you .... Hope you have enjoy reading my blog...