LAST_INSERT_ID

LAST_INSERT_ID is a SQL function that returns the first AUTO_INCREMENT value inserted into a table by the most recent statement. It's mainly used to get the unique identifier of an entry after it has been inserted into an AUTO_INCREMENT column in a MySQL database.

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

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

1

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”.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.