Saturday, November 27, 2004

How Do I get row number with SQL commands in MySQL?

Let's suppose we have a table look like this



Name PhoneNumber
-------------- --------------------
Peter        415-895-5689
John         408-854-4587
Louis        408-975-5986


And now I want to issue a SQL command which gives back a row number for each record which would look like this


RowNumber Name PhoneNumber
----------------- -------------------- ---------------------
1   Peter        415-895-5689
2   John         408-854-4587
3   Louis        408-975-5986


Under Oracle, this would be simple task, just issue the following SQL command
SELECT rownum, Name, PhoneNumber from table;
However, MySQL does not offer such convinience as rownum. In MySQL, we need to do the following instead.

mysql> SET @rownum := 0;

mysql> SELECT @rownum := @rownum + 1 AS RowNumber, Name, PhoneNumber from table;

Hope this tip can help you solve your current problem :)

No comments: