HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMajor

Is MySql's LAST_INSERT_ID() function guaranteed to be correct?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
functionmysqlcorrectguaranteedlast_insert_id

Problem

When I do a single row INSERT to a table that has an AUTO_INCREMENT column I'd like to use the LAST_INSERT_ID() function to return the new AUTO_INCREMENT'ed value stored for that row.

As many Microsoft SQL Server devs and admins no doubt are aware the equivalent functionality in SQL Server (SCOPE_IDENTITY and @@IDENTITY) hasn't been without its problems.

I know the MySQL docs state:


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_INCREMENTvalue 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.

(source)

and even go so far as to say:


Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid.

(source)

Are there any known risks or scenarios that may cause LAST_INSERT_ID() not to return the correct value?

I'm using MySQL 5.5 on CentOS 5.5 x64 and Fedora 16 x64 and the InnoDB engine.

Solution

A couple caveats I'd like to point out when using LAST_INSERT_ID:

-
I know you mentioned single-row inserts. But when doing multiple-row inserts, LAST_INSERT_ID() will return the value of the first row inserted (not the last).

-
If the insert failed, LAST_INSERT_ID() would be undefined. The same is true for automatic rollbacks of transactions (due to errors).

-
If you do an insert in a transaction that succeeds, and you still issue a ROLLBACK, LAST_INSERT_ID() would be left as it was prior to the rollback.

-
There are a couple caveats when using AUTO_INCREMENT and LAST_INSERT_ID in statement-based replication. The first being when used in a trigger or function. The second being the less-common scenario where your auto_increment column is part of a composite primary key and is not the first column in the key.

Context

StackExchange Database Administrators Q#21181, answer score: 39

Revisions (0)

No revisions yet.