Recently at work, I had to insert a row into a table and then get the id of the newly inserted row. I had planned on doing it as

Insert into table foo;

select max(id) from foo;

My colleague suggested a better approach

Insert into table foo;

select LAST_INSERT_ID();

What does this function do?

LAST_INSERT_ID() (with no argument) returns the first automatically generated value that was set for an AUTO_INCREMENT column by the most recently executed INSERT statement to affect such a column.

Advertisements