Home > Database > Mysql Tutorial > body text

How to Get the ID of Newly Created Records in MySQL?

Linda Hamilton
Release: 2024-11-20 16:00:14
Original
920 people have browsed it

How to Get the ID of Newly Created Records in MySQL?

Determining Identity of Newly Created Records in MySQL

When working with databases, it's often necessary to retrieve the unique identifier assigned to newly created records. In SQL Server, the SCOPE_IDENTITY() function serves this purpose. However, if you're using MySQL, its capabilities differ.

Equivalence in MySQL: LAST_INSERT_ID()

The MySQL equivalent of SCOPE_IDENTITY() is the LAST_INSERT_ID() function. It retrieves the ID of the last auto-increment value generated by the database.

Example Usage

CREATE TABLE Product (
  ProductID INT AUTO_INCREMENT PRIMARY KEY
);

INSERT INTO Product (Name) VALUES ('New Product');

# Get the ID of the newly created record
SELECT LAST_INSERT_ID();
Copy after login

This query will return the ProductID of the newly inserted record.

Note on Triggered Insertions

It's important to note that LAST_INSERT_ID() returns the ID of the last auto-increment generated within the current session or transaction. In the case of insert triggers that perform additional inserts, LAST_INSERT_ID() will return the ID of the original table, not the table that was inserted into during the trigger.

Conclusion

Understanding the MySQL equivalent of SQL Server functions is crucial for working effectively with cross-platform database applications. By utilizing LAST_INSERT_ID(), you can retrieve the identity of newly created records within MySQL.

The above is the detailed content of How to Get the ID of Newly Created Records 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