Difference between ROW_NUMBER(),RANK() and DENSE_RANK() function in SQL


Create table #tamp
(
EmpID  int identity(1,1) primary key(EmpID),
Name varchar(200),
Salary int
)


select * from #tamp

--insert into #tamp values('Rahul',10000)
--insert into #tamp values('Vishal',15000)
--insert into #tamp values('Mehul',20000)

--insert into #tamp values('Hiren',15000)
--insert into #tamp values('Amit',15000)
--insert into #tamp values('Mihir',20000)

ROW_NUMBER() Function keeps increasing integer by one and it is not caring duplicate values
RANK() and DENSE_RANK() functions are looking for duplicate values
RANK() Function The integer value is increasing by one but if the same value (Salary) is present in the table, then the same integer value is given to all the rows having the same value(Salary)

Select * ,
RANK() over (order by salary desc) as rank,
DENSE_RANK() over (order by salary desc) as denserank,
ROW_NUMBER() over (order by salary desc) as rownumber
from #tamp

In RANK function, the next row after the duplicate values (salary), will not give the integer value as next rank but instead of it, it skips those ranks and gives what is the next incremented rank. In the above case, the first three values are having same salary so it gives same rank to them but in next row, it gives as 4, It skips two and three as first three rows have same ranks.

In DENSE_RANK function, it will not skip any rank. This means the next row after the duplicate value (salary) rows will have the next rank in the sequence


Comments

Popular posts from this blog

Validate Mobile Number with 10 Digits in ASP.Net