Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: SQL
Expertise: Beginner
Jan 4, 2010

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

The 1998 tip "Displaying the Row Number in a SELECT Query" tells you to create a temp table to display the row numbers for a returned result set. That was an accepted solution for SQL Server 2000 and lesser versions.

Now SQL Server 2005ROW_NUMBEWR()that is very handy in scenarios where you want the result set to have row numbers assigned to each returned row. For example, take the same example given in the 1998 above tip:

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.

Find more info on ROW_NUMBER() here.

Deepak Choudhari
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap