MySQL LAST_INSERT_ID() Function

The LAST_INSERT_ID() function in MySQL retrieves the automatically generated ID from the most recent INSERT operation performed on a table with an AUTO_INCREMENT column.



LAST_INSERT_ID(): Definition and Usage

AUTO_INCREMENT columns automatically assign a unique, sequential integer value to each new row inserted into the table. LAST_INSERT_ID() is essential for getting this newly generated ID, which is often crucial for establishing relationships between tables or for further operations involving the newly inserted record.

Syntax

Syntax

LAST_INSERT_ID(expression)
      

The expression parameter is optional; if provided, it's used to set the value of the AUTO_INCREMENT counter; otherwise, the function returns the value of the last generated AUTO_INCREMENT ID.

Parameter Values

Parameter Description
expression (Optional) An expression used to set the AUTO_INCREMENT counter. If omitted, it returns the last generated AUTO_INCREMENT ID.

Example

Retrieving the Last Inserted ID

This query retrieves the ID of the last row inserted into a table with an AUTO_INCREMENT column. (You'll need to have performed an INSERT operation beforehand for this to work correctly.)

Syntax

SELECT LAST_INSERT_ID();
      
Output

(The last auto-incremented ID generated by an INSERT statement. Example: 10)
      

**Note:** The example output shows a sample `AUTO_INCREMENT` value (10). The actual value returned by `LAST_INSERT_ID()` will be the ID of the last row inserted into a table with an `AUTO_INCREMENT` column. You need to have previously executed an `INSERT` statement for this query to return a meaningful value. If no `INSERT` has been done, the output will be 0.