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