How to get ID of the last updated row in MySQL?

Avinash picture Avinash · Sep 7, 2009 · Viewed 181k times · Source

How do I get the ID of the last updated row in MySQL using PHP?

Answer

Pomyk picture Pomyk · Nov 17, 2009

I've found an answer to this problem :)

SET @update_id := 0;
UPDATE some_table SET column_name = 'value', id = (SELECT @update_id := id)
WHERE some_other_column = 'blah' LIMIT 1; 
SELECT @update_id;

EDIT by aefxx

This technique can be further expanded to retrieve the ID of every row affected by an update statement:

SET @uids := null;
UPDATE footable
   SET foo = 'bar'
 WHERE fooid > 5
   AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;

This will return a string with all the IDs concatenated by a comma.