Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL last_insert_id() and concurrency

Tags:

I have a simple MYSQL question. If I make a query that contains LAST_INSERT_ID() right after an INSERT QUERY running on a web page which has many concurrent users accessing other pages that perform INSERT operations would the value of LAST_INSERT_ID() be adulterated/corrupted?

like image 970
thegalah Avatar asked Jan 17 '14 12:01

thegalah


People also ask

Is MySQL LAST_INSERT_ID reliable?

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.

Is LAST_INSERT_ID thread safe?

So unless your inserts for multiple users would happen to be made over the same database connection, you have nothing to worry about.

What is LAST_INSERT_ID in MySQL?

The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

What does the function LAST_INSERT_ID () returns when no Auto_increment?

LAST_INSERT_ID() (no arguments) returns the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement. The value of LAST_INSERT_ID() remains unchanged if no rows are successfully inserted.


1 Answers

No, it will return the insert id from the current connection. As long as your script hasn't made any other inserts, you will get the one you want.

Also be aware that this will only return a generated ID (e.g. an auto-increment). If you are creating your own ID's it won't return this to you.

like image 81
charliefortune Avatar answered Nov 02 '22 23:11

charliefortune