Documentation Home
MySQL 9.4 C API Developer Guide
Download this Manual
PDF (US Ltr) - 1.4Mb
PDF (A4) - 1.4Mb


MySQL 9.4 C API Developer Guide  / ...  / Writing C API-Based Client Applications  / Using C API Features  /  Obtaining the Unique ID for the Last Inserted Row

3.6.11 Obtaining the Unique ID for the Last Inserted Row

If you insert a record into a table that contains anAUTO_INCREMENT column, you can obtain the value stored into that column by calling themysql_insert_id() function.

You can check from your C applications whether a value was stored in anAUTO_INCREMENT column by executing the following code (which assumes that you've checked that the statement succeeded). It determines whether the query was anINSERT with anAUTO_INCREMENT index:

if ((result = mysql_store_result(&mysql)) == 0 &&    mysql_field_count(&mysql) == 0 &&    mysql_insert_id(&mysql) != 0){    used_id = mysql_insert_id(&mysql);}

When a newAUTO_INCREMENT value has been generated, you can also obtain it by executing aSELECT LAST_INSERT_ID() statement withmysql_real_query() ormysql_query() and retrieving the value from the result set returned by the statement.

When inserting multiple values, the last automatically incremented value is returned.

ForLAST_INSERT_ID(), the most recently generated ID 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 anotherAUTO_INCREMENT column with a nonmagic value (that is, a value that is notNULL and not0). UsingLAST_INSERT_ID() andAUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid. Each client will receive the last inserted ID for the last statementthat 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 NULLINSERT INTO foo2 (id,text)    VALUES(LAST_INSERT_ID(),'text');  # use ID in second table

mysql_insert_id() returns the value stored into anAUTO_INCREMENT column, whether that value is automatically generated by storingNULL or0 or was specified as an explicit value.LAST_INSERT_ID() returns only automatically generatedAUTO_INCREMENT values. If you store an explicit value other thanNULL or0, it does not affect the value returned byLAST_INSERT_ID().

For more information on obtaining the last ID in anAUTO_INCREMENT column: