From the MySQL documentation on LAST_INSERT_ID()
and AUTO_INCREMENT
columns:
The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first
AUTO_INCREMENT
value generated for most recent statement affecting anAUTO_INCREMENT
column by that client. This value cannot be affected by other clients, even if they generateAUTO_INCREMENT
values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.
So, I've spent years panicking about race conditions in code like that below that apparently won't exist (at least in my cases):
`tbl`
------------------------
`id` INT AUTO_INCREMENT
`col` TEXT
INSERT INTO `tbl` (`col`) VALUES("lol");
SELECT LAST_INSERT_ID(); -- get `id` for inserted row
Perhaps you have, too?
Update
This is not explicitly the case for SQL_CALC_FOUND_ROWS
and FOUND_ROWS()
, though the following paragraph loosely implies that FOUND_ROWS()
is guaranteed to be ok after SQL_CALC_FOUND_ROWS
, at least within the same connection context:
The row count available through
FOUND_ROWS()
is transient and not intended to be available past the statement following theSELECT SQL_CALC_FOUND_ROWS
statement