The LAST_INSERT_ID() function in MySQL is used to retrieve the AUTO_INCREMENT value of the last row that was inserted or updated in a table.
Syntax
LAST_INSERT_ID()
or
LAST_INSERT_ID(expression)
Parameter Values
- expression: (Optional) An expression to update the value of the last inserted ID.
Definition and Usage
- The function returns the
AUTO_INCREMENTvalue of the most recent insert or update performed on a table in the current session. - It is especially useful when you need to know the ID of a row that has just been inserted into a table with an
AUTO_INCREMENTcolumn.
Technical Details
- Works in: From MySQL 4.0
Examples
Example 1: Get the last inserted ID
After inserting a row into a table, you can use the LAST_INSERT_ID() function to retrieve the AUTO_INCREMENT value generated for that row.
-- Insert a row into a table
INSERT INTO Customers (CustomerName, ContactName)
VALUES ('John Doe', 'John');
-- Get the last inserted ID
SELECT LAST_INSERT_ID();
Example Output:
1
This will return the AUTO_INCREMENT value (in this case, 1) of the row that was inserted into the Customers table.
Example 2: Use with UPDATE
You can also use LAST_INSERT_ID() to get the last inserted or updated AUTO_INCREMENT value, even after an UPDATE.
-- Update the row and retrieve the last inserted ID
UPDATE Customers
SET ContactName = 'Jane Doe'
WHERE CustomerID = 1;
SELECT LAST_INSERT_ID();
Example Output:
1
Usage Notes
- The function will return the
AUTO_INCREMENTvalue from the most recentINSERTorUPDATEin the current session, making it useful for managing relationships between tables (e.g., retrieving the ID of a newly inserted row for use in another table).