Thread safety of MySQL's Select Last_Insert_ID

9.9k views Asked by At

I'm trying to make some SQL Server code also run on MySQL, and I just hit this land mine. Google says the normal approach is to simply do your insert and then select last_insert_ID() to find out what got written.

This does not strike me as safe in a multi-user environment, though. There's a narrow window there where another user could insert something and cause a bad return value. How do I safely insert and obtain the key of the inserted record?

1

There are 1 answers

7
CBroe On BEST ANSWER

From LAST_INSERT_ID(), LAST_INSERT_ID(expr)

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 an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_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 unless your inserts for multiple users would happen to be made over the same database connection, you have nothing to worry about.