0

How would I get the row number of a mysql output, for example:

select * from table

name      age
David     12
Frank     13

I want to get the row number, like so:

select *, row_num from table

row    name      age
1      David     12
2      Frank     13

enter image description here

The row number on the left -- 1 through 7 -- not a part of the data itself.

David542
  • 104,438
  • 178
  • 489
  • 842
  • 1
    Typically there's a primary key value used for that. Should we assume no id/pk field? – Dan Jul 11 '16 at 22:51
  • @Dan yes, no primary key, I just want it to return the row number of the result. – David542 Jul 11 '16 at 23:10
  • 2
    @Dan does http://stackoverflow.com/questions/8509996/is-there-a-way-to-get-the-row-number-in-mysql-like-the-rownum-in-oracle do what you want? – Bryce Jul 11 '16 at 23:15
  • @Bryce I think you meant to ask the OP, not me – Dan Jul 11 '16 at 23:29

1 Answers1

1

In mysql, you have to use User-Defined Variables.

SELECT @rowno := @rowno + 1 AS row_no, *
FROM table
CROSS JOIN (SELECT @rowno := 0) t
-- ORDER BY age
Blank
  • 12,308
  • 1
  • 14
  • 32