Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL SELECT increment counter

Here is my MySQL query:

SELECT name FROM table; 

How can I also select an increment counter alongside name? Expected output:

Jay 1 roy 2 ravi 3 ram 4 
like image 888
iJade Avatar asked Nov 26 '12 14:11

iJade


People also ask

How do I increment a counter in MySQL?

To add an additional counter to your MySQL query result set, you need to create a variable using the SET statement first. Then, you need to increment the variable in your SELECT statement so that the variable value goes up for each row you have in the result set.

How do I increment a SQL SELECT statement?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

What is count (*) in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.

How do you implement a counter in SQL?

You can still use an identity column without changing your other tables. Something like CREATE TABLE counter (counter INT IDENTITY(1, 1) PRIMARY KEY ); , and then INSERT INTO counter DEFAULT VALUES; SELECT @@SCOPE_IDENTITY; DELETE FROM counter WHERE counter = @@SCOPE_IDENTITY; , perhaps?


1 Answers

select name,       @rownum := @rownum + 1 as row_number from your_table cross join (select @rownum := 0) r order by name 

This part:

cross join (select @rownum := 0) r 

makes it possible to introduce a variable without the need of a seperate query. So the first query could also be broken down into two queries like this:

set @rownum := 0;  select name,       @rownum := @rownum + 1 as row_number from your_table order by name; 

for instance when used in a stored procedure.

like image 160
juergen d Avatar answered Nov 04 '22 04:11

juergen d