top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Displaying the Row Number in a SELECT Query with SQL Server 2005

+2 votes

Displaying the Row Number in a SELECT Query was not easy with SQL 2000 or less where you need to create a temp table to display the row numbers for a returned result set. 

Now SQL Server 2005 ROW_NUMBEWR() that is very handy in scenarios where you want the result set to have row numbers assigned to each returned row. 

For example:

Select empname 
from employees 
where city = "toronto"

If you want the row_numbers to be displayed after this query is run, then use the ROW_NUMBER()function as below:

SELECT ROW_NUMBER() OVER(ORDER BY empname) AS 'row number', empname FROM employees WHERE city = "toronto"

When you run the above query, you will see results like those below. This avoids creating temp tables.

  1 Fred
  2 Bill
  3 Jeff
  4 June

What really happens here is that the ROW_NUMBER()assigns a unique number to each row to which it is applied (either each row in the partition or each row returned by the query), in the ordered sequence of rows specified in the order_by_clause, beginning with 1.

posted Jan 5, 2016 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.