SQL SERVER – 2005 – Sample Example of RANKING Functions – ROW_NUMBER, RANK, DENSE_RANK, NTILE

I have not written about this subject for long time, as I strongly believe that Book On Line explains this concept very well. SQL Server 2005 has total of 4 ranking function. Ranking functions return a ranking value for each row in a partition. All the ranking functions are non-deterministic.

ROW_NUMBER () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

RANK () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the rank of each row within the partition of a result set.

DENSE_RANK () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the rank of rows within the partition of a result set, without any gaps in the ranking.

NTILE (integer_expression) OVER ([<partition_by_clause>] <order_by_clause>)
Distributes the rows in an ordered partition into a specified number of groups.

All the above definition and syntax are taken from BOL. It is difficult to explain above function anything else than what they are explained in BOL. Following example is excellent example from BOL again. This function explains usage of all the four function together in one query.
USE AdventureWorks;
GO
SELECT c.FirstName, c.LastName
,ROW_NUMBER() OVER (
ORDER BY a.PostalCode) AS 'Row Number'
,RANK() OVER (
ORDER BY a.PostalCode) AS 'Rank'
,DENSE_RANK() OVER (
ORDER BY a.PostalCode) AS 'Dense Rank'
,NTILE(4) OVER (
ORDER BY a.PostalCode) AS 'Quartile'
,s.SalesYTD, a.PostalCode
FROM Sales.SalesPerson s
INNER JOIN Person.Contact c
ON s.SalesPersonID = c.ContactID
INNER JOIN Person.Address a
ON a.AddressID = c.ContactID
WHERE TerritoryID IS NOT NULL
AND
SalesYTD <> 0;

Resultset:
SQL SERVER - 2005 - Sample Example of RANKING Functions - ROW_NUMBER, RANK, DENSE_RANK, NTILE ranking

Most of the content of this article is taken from BOL.

Reference : Pinal Dave (https://blog.sqlauthority.com), ROW_NUMBER, RANK, DENSE_RANK, NTILE

Ranking Functions, SQL Function, SQL Scripts
Previous Post
SQL SERVER – 2005 – Connection Property of SQL Server Management Studio SSMS
Next Post
SQL SERVER – UDF vs. Stored Procedures and Having vs. WHERE

Related Posts

66 Comments. Leave new

  • Hi Pinal,

    Can we use ROW_NUMBER() function in views ?
    If not then what is the alternative method to give the row numbers in view

    Thanks
    -Sudhir

    Reply
    • Manoj Pandey
      April 9, 2010 9:49 am

      Very clearly described the definitions and example of all the 4. I was searching exactly this kind of concise & clear stuff.

      Dave, Thanks.

      -Manoj

      Reply
  • Hi Pinal,

    I have MS SQL 2000 on production server and as you know these functions are not available on same. My developer has used these functions extensively in application and insisting me to upgrade MS SQL 2000 to MS SQL 2005. This is not correct time for me to upgrade my system so can you please tell me the way out. Is it possible to use these functions in MS SQL 2000 by installing some patches or sp or by installing only t-sql of MS SQL 2005.

    Thanks

    Vikram

    Reply
  • azhar ali khan
    May 8, 2008 2:22 pm

    yes we can use try this……………..
    CREATE VIEW testview AS SELECT ROW_NUMBER() OVER (ORDER BY )-1 as autoIndex,

    * FROM

    Reply
  • azhar ali khan
    May 8, 2008 2:23 pm

    CREATE VIEW testview AS SELECT ROW_NUMBER() OVER (ORDER BY )-1 as autoIndex,

    * FROM

    Reply
  • hello,

    Please clafiry this doubt In MYSQL query can use like this
    select * FROM `table` WHERE MATCH (`email`) AGAINST (‘+firstname.lastname@hotmail.com’);
    where incase of MSSQL what quey can use to select record from database exact records ..for example in textbox i’m entering chennai,software,IT. i want all the records related to this string .. please reply

    Reply
  • Hi,

    It was an amazing article with apt example.
    AWESOME STUFF!!!

    Reply
  • how to get values like this is sqlserver query?

    Order Count,1,2,1-2,5,63,5-63,64,64,64,65,80,65-80,

    Reply
  • Hi Pinal,

    I try to determine the newest Price from multiple Items in a PriceTable. In Oracle, I can do this with ranking functions:

    SELECT ItemId, MAX(Price) KEEP(DENSE_RANK FIRST ORDER BY FromDate DESC) AS Price
    FROM PriceTable
    GROUP BY ItemId

    Is it possible to do the same with ranking functions in MSSQL?

    Thanks
    Martin

    Reply
  • Hi Pinal,
    I’m trying to convert these two rows to access sql.

    dense_rank() over(partition by field1 order by field2) as name1,

    row_number() over(partition by fld1, (dense_rank() over(partition by fldnm1 order by fldnm2)) order by fld2) as name2

    can you help me?
    thanks in advance

    Reply
  • hi sir,
    this is hanu, i have ony doubt that is

    how to store dense_rank() function results in sqlserver database.

    give me solution with example, thank u sir

    ex:

    sid same marks rank
    1 hanu 68 3
    2 bhanu 78 2
    3 ramu 80 1

    Reply
  • yogitha bali g.s
    October 17, 2009 4:20 pm

    Display the different types of credit caeds used for purchasing products?

    Reply
  • Imran Mohammed
    October 19, 2009 8:15 am

    @Yogitha bali g.s

    Question : Display the different types of credit caeds used for purchasing products?

    Answer :
    VISA
    MASTER
    AMERICAN EXPRESS
    Blah Blah….

    How I am I suppose to know this information.

    Please post your complete question, with complete details.

    ~ IM.

    Reply
  • hi ,
    Can u let me know how 2 ignore ranking if the column value is null.for e.g

    colX Rank
    52 7
    108 1
    80 2
    80 2
    null 8

    in the above case i want the ranking for 5th row to be null instead of 8.Need ur guidance

    Reply
    • As a quick reply (not sure if this is best). Add a WHERE clause ignoring NULLs, then UNION ALL to add the record that are NULL.

      Or, CASE colx WHEN NULL THEN NULL ELSE RANK….

      Reply
    • Hi Balaji,

      Yes you can ignore Null using the CASE condition before the RANK() function. I below pasted the code for your reference.
      SELECT * FROM dbo.EmpDetails
      I leaved one column(EmpSal) as null in this table.

      SELECT emp.EMPFName,(CASE WHEN emp.EMPSal is not null Then ROW_NUMBER()OVER(ORDER BY emp.EmpSal)ELSE NULL END) AS ‘Row Number’, RANK() OVER(ORDER BY emp.EmpSal)
      as ‘RANK’
      FROM dbo.EmpDetails emp

      Reply
  • Hi Pinal
    Can U explain briefly about NTILE Ranking function with an realtime example

    Reply
  • Sumit Kumar Gaud
    September 6, 2010 3:04 pm

    Hi Pinal,
    I want to get some amount of rows from a table, e.g. 10 rows, from 15th row in the table ordered by some column.
    how to use row_numberIO or any other functions

    Another Question:
    Can Identity Column is attached to select list in any select Query susch as

    select Identity(1,1) as row_number,col1,col2 from table1

    Reply
  • Your posts are very easy to understand.

    Thanks for the great article. It’s very useful to us.

    Reply
  • Hello – please help – I want to rank records in the table and store this rank in the same table for further processing – what is the simplest way to do it? I’m working in SQL 2005……

    Reply
  • Hi,
    I have strange requirement .

    I need to show ranks for all the rows except few in between.
    I tried that in using where id’s not in (‘1′,’2’)

    In this case I’m getting only the rows where id’s not in (1,2)

    Is there any way to get those rows as well in the same query ?

    Or Do I need to Follow a different approach?

    Reply
  • I have the same problem as anand has ..

    does any one has any solution ??

    Reply
  • Query

    I have a list of runners and their race times and ages. Write a
    Query to display the runners sorted by finish time with a column showing
    their finish position (ranking) within their age group.

    The age groups are
    0 – 15 years
    16 – 29 years
    30+ years

    Name Time Age
    ——————–
    Steve 12 33
    Tim 34 28
    Mark 22 37
    Tom 21 30
    Cliff 13 33
    Vini 17 28
    Matt 10 28
    Ben 9 29
    Brandon 15 14

    Output should be like below

    Name Time Age Ranking
    ===== ==== === =======
    Ben 9 29 1
    Matt 10 28 2
    Steve 12 33 1
    Cliff 13 33 2
    Brandon 15 14 1
    Vini 17 28 3
    Tom 21 30 3
    Mark 22 37 4
    Tim 34 28 4

    Reply
    • select Ranking,BloggerName from
      (select BloggerName,Row_Number() OVER (Partition by Topic Order by Total) ‘Ranking’
      FROM BlogCount where BloggerName=’Ritesh’) t where Ranking not in(2)

      Reply

Leave a Reply