Learn how to get row number in SQL. 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 2005 ROW_NUMBER() that is very handy in scenarios where you want the result set to have row numbers assigned to each returned row. For example of how to get row number in SQL, 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.