Name

LAST_INSERT_ID()

Synopsis

LAST_INSERT_ID([expression])

This function returns the identification number of the last row inserted using the MySQL connection. The identification number for rows inserted by other clients will not be returned. Identification numbers that are set manually when rows are inserted, without the aid of AUTO_INCREMENT, won’t register and therefore won’t be returned by LAST_INSERT_ID(). If multiple rows are inserted by one SQL statement, LAST_INSERT_ID() returns the identification number for the first row inserted.

Here is an example:

SELECT LAST_INSERT_ID( );

+-------------------+
| LAST_INSERT_ID( ) |
+-------------------+
|              1039 |
+-------------------+

As of version 5.1.12 of MySQL, an expression may be given to adjust the results. For instance, if you insert multiple rows of data, the result would be the value of the first row inserted, not the last. By giving an expression to include adding the number of rows, the results will be for the last row.

Get MySQL in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.