Ranking functions are used to assign rank to each and every row in a result set. There are four types of ranks offered by SQL Server 2008: ROW_NUMBER, RANK, DENSE_RANK and NTILE.
ROW_NUMBER is used to assign a number starting from 1 to n in the order specified by user. In spite of the column on which ROW_NUMBER to be applied is having repeated values, different row number is assigned to each row.
e.g.
Select * , (row_number() over(order by au_lname)) as [row_number] from pubs.dbo.authors;
e.g.
Select * , (row_number() over(order by au_lname)) as [row_number] from pubs.dbo.authors;
As shown in the above result set, row no. 17 and 18 has the same 'au_lname' but these have different row numbers.
row_number can also be used with an aggregate to provide sequencing within each group. This can be done using partition by clause e.g.
The following query partitions the rows based on the column 'city' and within each partition sorts the rows based on the column 'au_lname' .
select* , (row_number() over(partition by city order by au_lname)) as [row_number] from pubs.dbo.authors;
Each group starts row number from 1. Above result set is partitioned based on city. As one can see that city 'Berkeley' comes two times in the result set so first row with city 'Berkeley' has row_number 1 and the second row with the same city has row_number 2.
ROW_NUMBER in server side paging: Many times we have to display the information that spans across various web pages. In that case we want to display fixed no. of records from the result set at one time. Then comes the real application of row_number.
Below is the query that displays the rows starting from row number 7 till row number 20.
select *
from(select *, (row_number() over(order by au_lname)) as row_number from pubs.dbo.authors) as a
where row_number between 7 and 20;