I'm using AUTO_INCREMENT
and I would like to get that ID of inserted row so that I could update another table using ID
as common field between the 2 tables.
I understood that LAST_INSERT_ID
will get last ID
. However, my concern is that, the database is accessed at same time by many users. Hence, there might be another process accessed the table and also inserted a new row at same time.
Does LAST_INSERT_ID
return just the last ID regardless of the connection used, or only return last ID for the connection that I'm using?
Notice, I'm accessing MySQL database using connection pool in Tomcat server.
In summary, I need to insert a row in table A with auto increment, than I need to insert row in table B, which need to be linked to table A using the AUTO_INCREMENT
value.
Definition and Usage The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
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. and even go so far as to say: Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid.
The 'LAST_INSERT_ID()' function returns zero when no 'AUTO_INCREMENT' value has been generated during the current connection with the server.
SELECT max(employeeid) FROM Employee;
The above query returns the value of employeeid
of last inserted record in Employee table because employeeid
is an auto increment column. This seems to be OK, but suppose two threads are executing insert operation simultaneously, there is a chance that you get wrong id of last inserted record!
Don’t worry, MySQL provides a function which returns the value of auto increment column of last inserted record.
SELECT LAST_INSERT_ID();
LAST_INSERT_ID()
is always connection specific, this means even if insert operation is carried out simultaneously from different connections, it always returns the value of current connection specific operation.
So you have to first insert record in Employee table, run the above query to get the id value and use this to insert in second table.
LAST_INSERT_ID()
work in context, it should be in transactions or inside user defined stored procedures or user defined functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With