SQL Adding Row Number To The Returned Rows

Its something that took a bit of finding, but is very simple to do. I wanted to automatically add a row number to returned rows from a table in a database

e.g.

SELECT FirstNames, LastName, DOB FROM Staff ORDER BY FirstNames ASC

returns

FirstNames LastName DOB
Richard Taylor 01/01/1980
James Watts 01/01/1980
Richard Stringer 01/01/1980

we can modify this so that it returns a row number by changing the SQL as follows:

SELECT ROW_NUMBER() OVER (ORDER BY FirstNames) As RowNumber, FirstNames, LastName, DOB FROM Staff ORDER BY FirstNames ASC

now returns

RowNumber FirstNames LastName DOB
1 Richard Taylor 01/01/1980
2 James Watts 01/01/1980
3 Richard Stringer 01/01/1980

NB. The ROW_NUMBER() Requires that the over keyword be included after it, and that the order you choose should be the same as the order by on the query.

If you know how to do this in a different way, or a way that will work for a query that does not have an order by (a very rare occurence) then please do post a comment to let others know.

Leave a Reply