tags:

views:

266

answers:

5

This is a sql newbie question.

Basically, I want an extra column to return with my select statement to number the rows. I'm using mysql.

Eg:

select * from friends

David
Steve
Joe

What is the syntax to get:

1  David
2  Steve
3  Joe
A: 

In SQL Server 2005 and higher you can use the Row_Number function.

YonahW
Dunno why this got a down-vote; it is probably the closest thing to a standard SQL answer (for all that not every DBMS has implemented it).
Jonathan Leffler
Because its not about standard SQL. He clearly states that he is using MySQL. I was not the one who cast the down vote, though.
Adeel Ansari
Others stated solutions for Oracle or MS SQL Server without getting down-voted. This answer is not worse than theirs.
Tomalak
Just for the record the question did not originally state MySQL. When I answered the question there was not mention whatsoever of which RDBMS was being used. You can check the edit history to see for yourself.
YonahW
Actually, no - at the time the answer was posted, it did not say MySQL. That was an extra tag added, and a title changed.
Jonathan Leffler
A: 

I'll do this in a stored proc

CREATE TABLE #Foo (
  [FooId] [int] IDENTITY(1,1) NOT NULL,
  [Name] varchar(255)
)

SELECT *
FROM Friends
INTO #Foo

SELECT *
FROM #Foo
eed3si9n
+4  A: 

From: http://markmal.blogspot.com/2006/04/oracle-like-rownum-in-mysql.html

SELECT @rownum:=@rownum+1 rownum, t.*FROM (SELECT @rownum:=0) r, mytable t;
Paul Tomblin
Thanks. This works perfectly in mysql.
Yada
A: 

As you might have guessed from the divergent responses you've received, the answer depends on which DBMS you are using. However, the answer typically involves ROWNUM or a variant on that spelling.

The standard SQL answer is probably ROW_NUMBER() - mentioned by @YonahW; it works as a windowing function and is not available in all DBMS.

Jonathan Leffler
And it is not available until SQL Server 2005, IIRC.
Tomalak
+1  A: 

If you are developing some application, its better to get the number of records from your result set or data set or any container you are using to hold the result, instead. The basic idea is to do it in your code. Otherwise, Paul solution will work in your case.

In MySql, there is nothing like ROWNUM, what we have in Oracle, and neither we have Row_Number(), what we have in MS SQL Server, nor any other variant.

Edit:

By doing it in your code, you need not change your SQL statement, if the underlying database changes, just because of this reason.

Adeel Ansari