Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a counter and return the value in MySQL

Tags:

select

mysql

I have a table that has a Key column and a Counter column. I need to do something like this:

SELECT counter=counter+1 FROM table WHERE key='mykey'

Basically, I need to increment the Counter column and return the new value. How can I do this in MySQL 5.5?

like image 494
Jon Tackabury Avatar asked May 27 '11 14:05

Jon Tackabury


People also ask

How do I increment a counter in MySQL?

In MySQL, auto increment counter starts from 0 by default, but if you want the auto increment to start from another number, use the below syntax. ALTER TABLE yourTable auto_increment=yourIntegerNumber; To understand the above syntax, let us first create a table.

What is counter in MySQL?

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

What is increment in database?

Auto Increment is a function that operates on numeric data types. It automatically generates sequential numeric values every time that a record is inserted into a table for a field defined as auto increment.


1 Answers

update mytable set count=last_insert_id(counter+1) where key='mykey'

Then

select last_insert_id()

last_insert_id() can be passed an argument to 'set' it (and return that value), and calling it without an argument will return the value again. The internal state used by last_insert_id() is per-connection, which means that the same update statement issued on another connection will not affect the first.

Reference: last_insert_id()

like image 96
Joel B Fant Avatar answered Oct 07 '22 22:10

Joel B Fant