SQL Server – Ranking Functions – RANK, DENSE_RANK, ROW_NUMBER, NTILE
Ranking functions return a ranking value for each row in a partition. Depending on the function that is used, some rows might receive the same value as other rows. Ranking functions are nondeterministic.
There are four functions
- RANK
- DENSE_RANK
- ROW_NUMBER
- NTILE
RANK
Returns the rank of each row within the partition of a result set. The rank of a row is one plus the number of ranks that come before the row in question.
DENSE_RANK
Returns the rank of rows within the partition of a result set, without any gaps in the ranking. The rank of a row is one plus the number of distinct ranks that come before the row in question.
ROW_NUMBER
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
NTILE
Distributes the rows in an ordered partition into a specified number of groups. The groups are numbered, starting at one. For each row, NTILE returns the number of the group to which the row belongs.
Difference between the RANK and DENSE_RANK
RANK leaves gaps while ranking the records whereas DENSE_RANK doesn’t leave any gaps and always have consecutive ranks.
So may you have questioned which one to use?
It’s all depends on your requirement and business rule you are following.
Choice between RANK and DENSE_RANK depends on the business rules you are following. As mentioned above RANK leaves gaps while ranking the records whereas DENSE_RANK doesn’t leave any gaps.
ROW_NUMBER to be used only when you just want to have the serial number on result set.
NTILE to be used when you want to distributes the rows in an ordered partition into a specified number of groups.
For more details you can refer the MSDN