00 Votes

MySQL: Number Rows in the Result

Question by Guest | 2016-04-23 at 21:00

I am retrieving some data from my MySQL database and I would like to number the data records respectively rows in the result from 1 to the number of data sets.

Please consider that I do not want to do this using PHP or something like that later. Instead, I directly want to get the numbering in the MySQL result so that there is a number before each line. Is that possible?

ReplyPositiveNegative
0Best Answer0 Votes

Yes, that is possible. Just have a look at the following example.

Here, we are reading out the data from the columns "col1" and "col2" from the table "tab" and additionally we are creating a line number. We have given the table tab the alias t, so that we are writing t.col1 and t.col2 in the example.

SELECT (@row := @row + 1) as rownr, t.col1, t.col2
FROM tab t, (SELECT @row := 0) r

We are getting the numbering with defining a variable "row" using "SELECT @row := 0" in order to increase this variable by one at each line (@row := @row + 1) and returning the result of this calculation as "rownr".
2016-04-24 at 11:53

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.