As mentioned in the manual:
LAST_INSERT_ID()
(with no argument) returns a BIGINT
(64-bit) value representing 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. For example, after inserting a row that generates an AUTO_INCREMENT
value, you can get the value like this:
mysql>SELECT LAST_INSERT_ID();
->195
The currently executing statement does not affect the value of
LAST_INSERT_ID()
. Suppose that you generate an AUTO_INCREMENT
value
with one statement, and then refer to LAST_INSERT_ID()
in a
multiple-row INSERT
statement that inserts rows into a table with its
own AUTO_INCREMENT
column. The value of LAST_INSERT_ID()
will remain
stable in the second statement; its value for the second and later
rows is not affected by the earlier row insertions. (However, if you
mix references to LAST_INSERT_ID()
and LAST_INSERT_ID(expr)
, the
effect is undefined.)
If the previous statement returned an error, the value of
LAST_INSERT_ID()
is undefined. For transactional tables, if the
statement is rolled back due to an error, the value of
LAST_INSERT_ID()
is left undefined. For manual ROLLBACK, the value of
LAST_INSERT_ID()
is not restored to that before the transaction; it
remains as it was at the point of the ROLLBACK.
So, LAST_INSERT_ID()
is always transaction-safe (even though you don't use transaction).