MariaDB LAST_INSERT_ID() Function
With no arguments, the MariaDB LAST_INSERT_ID() function returns the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement. The value of LAST_INSERT_ID() remains unchanged if no rows are successfully inserted.
With an argument, this function will return the value of the expression and the next call to LAST_INSERT_ID() will return the same value.
Syntax
LAST_INSERT_ID(expression)
Parameters
expression |
Optional. If it is specified, the value of the expression is returned and remembered as the next value to be returned by the LAST_INSERT_ID() function. |
Return Value
Returns the AUTO_INCREMENT ID of the last row that has been inserted or updated in a table.
Example:
Consider the example below, where a table called Employee is created with an AUTO_INCREMENT field called EmpID. After creating the table, the LAST_INSERT_ID() function is used to get the AUTO_INCREMENT ID in various scenarios.
CREATE TABLE Employee ( EmpID INT AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(50)); SELECT LAST_INSERT_ID(); +------------------+ | LAST_INSERT_ID() | +------------------+ | 0 | +------------------+ INSERT INTO Employee(Name) Values ('John'); INSERT INTO Employee(Name) Values ('Marry'); SELECT LAST_INSERT_ID(); +------------------+ | LAST_INSERT_ID() | +------------------+ | 2 | +------------------+ INSERT INTO Employee(Name) Values ('Kim') , ('Jo'); SELECT LAST_INSERT_ID(); +------------------+ | LAST_INSERT_ID() | +------------------+ | 3 | +------------------+ SELECT * FROM Employee; +-------+-------+ | EmpID | Name | +-------+-------+ | 1 | John | | 2 | Marry | | 3 | Kim | | 4 | Jo | +-------+-------+ SELECT LAST_INSERT_ID(10); +--------------------+ | LAST_INSERT_ID(10) | +--------------------+ | 10 | +--------------------+ SELECT LAST_INSERT_ID(); +------------------+ | LAST_INSERT_ID() | +------------------+ | 10 | +------------------+ INSERT INTO Employee(Name) Values ('Ramesh'); SELECT LAST_INSERT_ID(); +------------------+ | LAST_INSERT_ID() | +------------------+ | 5 | +------------------+ SELECT * FROM Employee; +-------+--------+ | EmpID | Name | +-------+--------+ | 1 | John | | 2 | Marry | | 3 | Kim | | 4 | Jo | | 5 | Ramesh | +-------+--------+
❮ MariaDB Functions