Home >Database >Mysql Tutorial >How to Get the Auto-Generated ID After an INSERT Query in MySQL?
How to Retrieve Auto-Generated Primary Key ID from MySQL INSERT Query
Inserting data into MySQL tables with auto-incrementing primary keys presents the challenge of retrieving the newly generated ID. This question addresses this issue, inquiring about the best approach to obtain the primary key value within the same query.
Solution: LAST_INSERT_ID() Function
The MySQL LAST_INSERT_ID() function provides an elegant solution to this problem. By using this function, developers can retrieve the ID of the last row that they inserted into the database, allowing them to work with the newly created record effectively.
Implementation
To use LAST_INSERT_ID(), simply add it after the INSERT statement as shown in the example below:
INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...); SELECT LAST_INSERT_ID();
This will return the primary key value of the newly inserted row.
Per-Connection Basis
It's important to note that LAST_INSERT_ID() operates on a per-connection basis, meaning that the value returned is specific to the user who executed the INSERT statement. This ensures that multiple users updating the same table concurrently will not interfere with each other's ID generation.
Advantages
Using LAST_INSERT_ID() within the INSERT query offers several advantages:
By incorporating LAST_INSERT_ID() into your MySQL INSERT queries, you can efficiently obtain the newly generated primary key values, providing you with the necessary data to work with your newly inserted records.
The above is the detailed content of How to Get the Auto-Generated ID After an INSERT Query in MySQL?. For more information, please follow other related articles on the PHP Chinese website!