Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I update an INT value + 1 and return the new value?

Tags:

php

int

mysql

Is it possible in MySQL+PHP to increase an INT value and return the new value within one query?

$sql = mysql_query("UPDATE table SET number=number+1 WHERE id='uniqid'");

$updated_number = ???

Or I need to post another query?

SELECT number FROM table WHERE id='uniqid'
like image 286
lukeshek Avatar asked Nov 22 '11 18:11

lukeshek


People also ask

How UPDATE query works in MySQL?

For the single-table syntax, the UPDATE statement updates columns of existing rows in the named table with new values. The SET clause indicates which columns to modify and the values they should be given. Each value can be given as an expression, or the keyword DEFAULT to set a column explicitly to its default value.

How to UPDATE a column in MySQL?

MySQL UPDATE multiple columnsMySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated.


1 Answers

Simple answer - no, it's not possible.

Longer answer, yes, if you use a stored procedure that increments the value for the specified ID, retrieves the new value and returns it.

I've just tested this under MySQL 5.1.59:

CREATE PROCEDURE increment (IN uniqid VARCHAR(255))
BEGIN
   UPDATE `table` SET number = number + 1 WHERE id = uniqid;
   SELECT number FROM `table` WHERE id = uniqid;
END

Usage:

CALL increment(uniqid)

If multiple simultaneous accesses are possible you may wish to LOCK the table first to ensure the operation's atomicity - MySQL apparently doesn't allow stored procedures to lock tables themselves.

like image 89
Alnitak Avatar answered Oct 27 '22 01:10

Alnitak