"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Get the ID of Newly Created Records in MySQL?

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

Published on 2024-11-25
Browse:474

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();

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3