Home >Database >Mysql Tutorial >How Can I Efficiently Retrieve a Newly Generated Auto-Incrementing Primary Key in MySQL?
Retrieving Newly Generated Primary Key in MySQL Insert Queries
When inserting records into a MySQL table with an auto-incrementing primary key, it can be necessary to retrieve the generated primary key value for further processing or referencing. Instead of relying on a separate query to retrieve the ID, which can lead to potential errors, there is a more efficient way to obtain the primary key directly from the insert query.
To achieve this, MySQL provides the LAST_INSERT_ID() function. This function returns the primary key value of the most recently inserted row for the current connection. By incorporating LAST_INSERT_ID() into the insert query, it is possible to retrieve the generated primary key immediately.
Syntax:
INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...); SELECT LAST_INSERT_ID();
In this example, the first query inserts a new record into the specified table. The second query retrieves the primary key value generated during the insertion process.
Important Considerations:
The above is the detailed content of How Can I Efficiently Retrieve a Newly Generated Auto-Incrementing Primary Key in MySQL?. For more information, please follow other related articles on the PHP Chinese website!