LAST_INSERT_ID
LAST_INSERT_ID([expr])
Section titled “LAST_INSERT_ID([expr])”- expr: This is an optional argument. If expr is given, it generates the next AUTO_INCREMENT value that will be used by the AUTO_INCREMENT column. This applies to the most recent connection that sent the INSERT command. If no expr is specified, LAST_INSERT_ID() returns the most recently generated AUTO_INCREMENT value.
Example
Section titled “Example”CREATE TABLE Books ( id INT AUTO_INCREMENT, title VARCHAR(255), PRIMARY KEY(id));
INSERT INTO Books (title) VALUES ('Book 1');
SELECT LAST_INSERT_ID();Output
Section titled “Output”1Explanation
Section titled “Explanation”The LAST_INSERT_ID() function is used to retrieve the ID which was automatically generated by the most recently executed INSERT statement. In the above example, it returns “1” because the id for ‘Book 1’ in the ‘Books’ table is “1”.