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

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.

Leave a Comment