Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL LAST_INSERT_ID() used with multiple records INSERT statement

If I insert multiple records with a loop that executes a single record insert, the last insert id returned is, as expected, the last one. But if I do a multiple records insert statement:

INSERT INTO people (name,age) VALUES ('William',25), ('Bart',15), ('Mary',12); 

Let's say the three above are the first records inserted in the table. After the insert statement I expected the last insert id to return 3, but it returned 1. The first insert id for the statement in question.

So can someone please confirm if this is the normal behavior of LAST_INSERT_ID() in the context of multiple records INSERT statements. So I can base my code on it.

like image 215
bogdan Avatar asked Jan 09 '11 02:01

bogdan


People also ask

Can we insert multiple records in MySQL?

Introduction to the MySQL INSERT statementThe INSERT statement allows you to insert one or more rows into a table.

What will be the value of LAST_INSERT_ID () for the newly created table?

With no argument, LAST_INSERT_ID() returns a 64-bit value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement.

What is LAST_INSERT_ID in MySQL?

The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

Is MySQL LAST_INSERT_ID reliable?

This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions. and even go so far as to say: Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid.


Video Answer


2 Answers

Yes. This behavior of last_insert_id() is documented in the MySQL docs:

Important
If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.

like image 166
Asaph Avatar answered Sep 23 '22 22:09

Asaph


This behavior is mentioned on the man page for MySQL. It's in the comments but is not challenged, so I'm guessing it's the expected behavior.

like image 33
Larry Lustig Avatar answered Sep 25 '22 22:09

Larry Lustig