W3docs

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

To get the ID of the last inserted row, you can use the LAST_INSERT_ID() function.

To get the ID of the last inserted row, you can use the LAST_INSERT_ID() function. For example:

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

INSERT INTO table (col1, col2) VALUES(val1, val2);
SELECT LAST_INSERT_ID();

This will insert a new row into the table table and then return the ID of the last inserted row.

If you want to get the ID of the last updated row, note that LAST_INSERT_ID() does not work for UPDATE statements. In MySQL 8.0.21+, you can use the RETURNING clause to retrieve the updated row's ID directly:

Example of getting the ID of the last updated row in MySQL

UPDATE table SET col1 = val1 WHERE id = 5 RETURNING id;

This updates the specified row and returns its ID. If you are using an older MySQL version, you typically already know the ID from your WHERE clause, or you can run a SELECT statement with the same conditions before or after the update.

Note that the LAST_INSERT_ID() function returns the last ID generated by an AUTO_INCREMENT INSERT statement on the current connection. It does not track IDs modified by UPDATE statements, so you will need to use the RETURNING clause or query the row directly when working with updates.

I hope this helps! Let me know if you have any questions.