How do I write a query that outputs the row number as a column?

nearly_lunchtime picture nearly_lunchtime · Jan 13, 2009 · Viewed 58.9k times · Source

How do I write a query that outputs the row number as a column? This is DB2 SQL on an iSeries.

eg if I have

table Beatles:

John
Paul
George
Ringo

and I want to write a statement, without writing a procedure or view if possible, that gives me

1 John
2 Paul
3 George
4 Ringo

Answer

Michael Buen picture Michael Buen · Jan 13, 2009
SELECT ROW_NUMBER() OVER (ORDER BY beatle_name ASC) AS ROWID, * FROM beatles