Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How Do I Get a Row Number On Each Row of a Query Result Set?

T-SQL Hints and Tips

How Do I Get a Row Number On Each Row of a Query Result Set?

by  tlbroadbent  Posted    (Edited  )

It is often desirable to have a row number on each row of a query result set. Unfortunately, T-SQL doesn't provide RowNum like you will find in Oracle. Here are a couple of methods for adding a row number column.

For small tables use a sub-query to count the rows up to and including the current row. An assumption is made that there is a primary key or unique index on the table.

--Assume the primary key is a composite of Col1 and Col2.
Select
RowNum=(Select Count(*) From TableName
Where Col1<=t1.Col1 And Col2 <=t1.Col2)
Col1, Col2, Col3, Col4
From TableName t1
Order By Col1, Col2

For larger tables it is usually faster to insert the rows selected into a temp table with an identity column, and then select from the temp table.

Create table #temp
(Col1 varchar(10),
Col2 varchar(10),
Col3 Int,
Col4 Decimal(12,2),
RowNum Int Identity)

Insert #temp(Col1, Col2, Col3, Col4)
Select Col1, Col2, Col3, Col4 From TableName
Order By Col1, Col2

Select RowNum, Col1, Col2, Col3, Col4
From #temp
Order By RowNum

Neither of these methods is very efficient but will provide a row number when needed. If you have another method that you prefer to use, please let me know. Any other comments or recommendations are welcome.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top