Home >Database >Mysql Tutorial >How to Retrieve the Auto-Generated Primary Key After an INSERT in MySQL?

How to Retrieve the Auto-Generated Primary Key After an INSERT in MySQL?

Linda Hamilton
Linda HamiltonOriginal
2024-12-13 09:15:12239browse

How to Retrieve the Auto-Generated Primary Key After an INSERT in MySQL?

Retrieving Primary Key ID from MySQL INSERT Query

Question: How can I retrieve the newly generated primary key ID for an inserted record in the same query?

Answer: To obtain the primary key ID of the newly inserted record in MySQL, utilize the LAST_INSERT_ID() function. Syntax:

INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...);
SELECT LAST_INSERT_ID();

This function retrieves the last generated primary key value for the current user connection. It provides:

  • Per-connection basis: The returned ID applies to the last inserted row within the current user's connection.
  • Unaffected by other queries: Other queries from different users do not impact the LAST_INSERT_ID() value maintained by the server for the specific user connection.

The above is the detailed content of How to Retrieve the Auto-Generated Primary Key After an INSERT in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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