LAST_INSERT_ID() : SQL Informative Function

  • It returns the the most recently generated ID that is maintained in the server on a per-connection basis.  
  • It is not changed by another client. It is not even changed if you update another AUTO_INCREMENT column with a nonmagic value (that is, a value that is not NULL and not 0).
  • Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid as each client will receive the last inserted ID for the last statement that client executed.

If you want to use the ID that was generated for one table and insert it into a second table, you can use SQL statements like this:

INSERT INTO foo (auto,text) VALUES (NULL,'text');         // generate ID by inserting NULL
INSERT INTO foo2 (id,text) VALUES (LAST_INSERT_ID(),'text');  // use ID in second table 

BEWARE !!

1) However, you might be getting incorrect output if you try these SQL commands on a browser based SQL interface like phpMyadmin or MySQL Query Browser. This is because these interfaces create a separate connection every time a query is created. So, every time you will see that LAST_INSERT_ID() returns 0 (zero). To, avoid this, you should execute both the queries in a single line, separated by semicolons.

INSERT INTO foo (auto,text) VALUES (NULL,'text'); INSERT INTO foo2 (id,text) VALUES (LAST_INSERT_ID(),'text');

2) Also, LAST_INSERT_ID() returns 0 in a case where you do not have an AUTO_INCREMENT column in your database. So, before executing this query, make sure that you do have one in your database.

For more information, visit :
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html

Comments

Popular Posts