The LAST_INSERT_ID()
function only returns the most recent autoincremented id value for the most recent INSERT
operation, to any table, on your MySQL connection.
If you haven't just done an INSERT
it returns an unpredictable value. If you do several INSERT
queries in a row it returns the id of the most recent one. The ids of the previous ones are lost.
If you use it within a MySQL transaction, the row you just inserted won't be visible to another connection until you commit the transaction. So, it may seem like there's no row matching the returned LAST_INSERT_ID()
value if you're stepping through code to debug it.
You don't have to use it within a transaction, because it is a connection-specific value. If you have two connections (two MySQL client programs) inserting stuff, they each have their own distinct value of LAST_INSERT_ID()
for the INSERT
operations they are doing.
edit If you are trying to create a parent - child relationship, for example name and email addresses, you might try this kind of sequence of MySQL statements.
INSERT INTO user (name) VALUES ('Josef');
SET @userId := LAST_INSERT_ID();
INSERT INTO email (user_id, email) VALUES (@userId, '[email protected]');
INSERT INTO email (user_id, email) VALUES (@userId, '[email protected]');
This uses LAST_INSERT_ID()
to get the autoincremented ID from the user
row after you insert it. It then makes a copy of that id in @userId
, and uses it twice, to insert two rows in the child table. By using more INSERT INTO email
requests, you could insert an arbitrary number of child rows for a single parent row.
Pro tip: SELECT MAX(id) FROM table
is a bad, bad way to figure out the ID
of the most recently inserted row. It's vulnerable to race conditions. So it will work fine until you start scaling up your application, then it will start returning the wrong values at random. That will ruin your weekends.
LAST_INSERT_ID()
because it will return the correct ID when you have transactions – Busteeid = 5
and then delete it from the table? – Caabaselect max(id) from table
– Pettiford