MySQL LAST_INSERT_ID

The MySQL LAST_INSERT_ID() function returns the most recently generated integer successfully inserted for an AUTO_INCREMENT column.

 

CREATE TABLE user(
    id INT AUTO_INCREMENT,
    name VARCHAR(250) NOT NULL
    ...,
    PRIMARY KEY(id)
);

If you insert multiple rows into the table using a single INSERT statement, the LAST_INSERT_ID() function returns the first automatically generated value only.

If the insertion fails, the result returned by the LAST_INSERT_ID() remain unchanged.

The LAST_INSERT_ID() function works based on client-independent(database connection) principle. It means the value returned by the LAST_INSERT_ID() function for a specific client is the value generated by that client only to ensure that each client can obtain its own unique ID. This means that each database connection will have its own LAST_INSERT_ID().

INSERT INTO user(name)
VALUES('Folau');
SELECT LAST_INSERT_ID();

The result is 1 which is the first id in the table.

 

 

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *