Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

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 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: http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_last-insert-id)

and even go so far as to say:

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

(source: http://dev.mysql.com/doc/refman/5.5/en/getting-unique-id.html)

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.

share|improve this question
2  
I wouldn't submit this as an answer but we're doing millions of inserts each day using AUTO_INCREMENT and LAST_INSERT_ID. So far we've never had any issues with that. –  tex Jul 19 '12 at 17:51
    
Is this theoretical or are you having an issue that you suspect this is the case? –  rfusca Jul 19 '12 at 18:06
    
@rfusca - just making sure I am avoiding risk by committing to using LAST_INSERT_ID() if there are known problems. –  Kev Jul 19 '12 at 22:41
    
@tex, How would you know if there's a problem? –  Pacerier yesterday

2 Answers 2

up vote 21 down vote accepted

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

  1. 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).

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

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

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

share|improve this answer
2  
Very nice list of gotchas. +1 !!! –  RolandoMySQLDBA Jul 19 '12 at 18:09
    
Appreciated, especially item 4 as we're replicating the production server. –  Kev Jul 20 '12 at 1:06

To expand further on point number 2 in the answer given by DTest:

On the versions of MySQL that I have used, it is a good idea to explicity reset the value of LAST_INSERT_ID prior to each block of code where you plan to perform an insert.

This can be done like so:

-- initialize the LAST_INSERT_ID to some flag value:
SELECT LAST_INSERT_ID( some_flag_init_value_of_your_choice );
-- perform the insert  
INSERT INTO ttt (ccc) VALUES (vvv);
-- retrieve the id of the inserted row:  
SELECT LAST_INSERT_ID();

After the above series of statements is executed, you will know whether the insert had any affect by checking whether LAST_INSERT_ID was still set to "some_flag_init_value_of_your_choice" at the end of execution.

Otherwise, you can wind up with the following problematic situation:

INSERT INTO ttt ( ccc ) VALUES ( 'a' );    -- assume this succeeds.
SELECT LAST_INSERT_ID();                   -- this will return the unique id of the new row with value 'a'.
INSERT INTO ttt ( ccc ) VALUES ( 'b' );    -- assume this FAILS.
SELECT LAST_INSERT_ID();                   -- this will STILL RETURN the unique id of the row with 'a'.

Because the second insert has failed, you may have been expecting that the second call to LAST_INSERT_ID would either return NULL or that it would produce an empty result set (zero rows). The fact that it still returns a valid integer identifier may mislead you into thinking that the second insert SUCCEEDED when it did not.

Things get EVEN WEIRDER when you consider that LAST_INSERT_ID will continue to preserve and repeat the last successful unique id even if subsequent failing insert statements are targeting different tables than the table that produced the last successful unique id. In other words, you insert into table TA and get an id of 5, then you insert into TB (but it fails), but you still see a 5. Based on that, you think that you have just created a new row in TA with id of 5 and a new row in TB with id of 5, whereas in reality there either does not exist any row in TB with id 5, or there does exist such a row but it actually has nothing to do with any code you just ran.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.