Home > Database > Mysql Tutorial > How does LAST_INSERT_ID() behave with multiple record INSERT statements in MySQL?

How does LAST_INSERT_ID() behave with multiple record INSERT statements in MySQL?

Mary-Kate Olsen
Release: 2024-11-17 11:48:01
Original
578 people have browsed it

How does LAST_INSERT_ID() behave with multiple record INSERT statements in MySQL?

LAST_INSERT_ID() Behavior with Multiple Record INSERT Statements

When inserting multiple records into a MySQL table with a single INSERT statement, LAST_INSERT_ID() typically returns the ID of the first inserted record rather than the last.

As confirmed in the MySQL documentation, this behavior ensures that the INSERT statement can be reproduced accurately on other servers. The ID value for subsequent records is not returned because it cannot be consistently assigned across different database servers.

Example:

Consider the following INSERT statement:

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

After executing this statement, LAST_INSERT_ID() will return 1, the ID of the first inserted record (William). This is the expected behavior and ensures that the statement can be replicated without unintended results.

Implications:

In code that handles multiple record insertions, it's important to be aware of this behavior and handle the ID values accordingly. For example, if you need to retrieve the IDs of all inserted records, you may need to use another approach, such as returning the inserted row count and then retrieving the IDs individually.

The above is the detailed content of How does LAST_INSERT_ID() behave with multiple record INSERT statements in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template