MySQL: LAST_INSERT_ID()

In: MySQL

26 May 2010

If you use LAST_INSERT_ID() and insert on the primary key value it will only return the last “insert id” which has not included the primary key

DROP TABLE IF EXISTS `example`;
CREATE TABLE IF NOT EXISTS `example` ( id INT(11) NOT NULL AUTO_INCREMENT, b CHAR(3), PRIMARY KEY(id)) ENGINE=InnoDB;
INSERT INTO example SET id=1;
INSERT INTO example SET id=2;
INSERT INTO example SET id=3;
SELECT LAST_INSERT_ID(); # outputs 0
INSERT INTO example SET b=1;
INSERT INTO example SET b=2;
INSERT INTO example SET b=3;
SELECT LAST_INSERT_ID(); # outputs 6

LAST_INSERT_ID will also persist its value, and also in addition you can set the value with an expression.

TRUNCATE example;
SELECT LAST_INSERT_ID(); # outputs 6
SELECT LAST_INSERT_ID(0); # use an expression, outputs 0

BEGIN;
INSERT INTO example SET b=1;
INSERT INTO example SET b=2;
INSERT INTO example SET b=3;
SELECT LAST_INSERT_ID(); # outputs 3
ROLLBACK;
SELECT LAST_INSERT_ID(); # outputs 3

Comment Form

About this blog

I have been a developer for roughly 10 years and have worked with an extensive range of technologies. Whilst working for relatively small companies, I have worked with all aspects of the development life cycle, which has given me a broad and in-depth experience.