Home > Database > Mysql Tutorial > What\'s the MySQL Equivalent of SQL Server\'s SCOPE_IDENTITY()?

What\'s the MySQL Equivalent of SQL Server\'s SCOPE_IDENTITY()?

Patricia Arquette
Release: 2024-12-01 03:25:12
Original
762 people have browsed it

What's the MySQL Equivalent of SQL Server's SCOPE_IDENTITY()?

MySQL Equivalent of SQL Server's SCOPE_IDENTITY()

When working with auto-incrementing columns in MySQL, you may encounter a need to retrieve the ID of the last inserted record, analogous to the SCOPE_IDENTITY() function in SQL Server. This article explores the equivalent in MySQL and provides detailed examples for its usage.

Equivalent of SCOPE_IDENTITY() in MySQL

The equivalent function in MySQL is LAST_INSERT_ID(). This function returns the last auto-incrementally generated value for the most recent insert operation executed within the current connection.

Usage Example

Consider the following MySQL code:

INSERT INTO Customers (Name, Email) VALUES ('John Doe', 'john.doe@example.com');
SELECT LAST_INSERT_ID();
Copy after login

The first statement inserts a new record into the Customers table and assigns an auto-incrementing ID to the newly added row. The second statement retrieves the ID of the last inserted record using the LAST_INSERT_ID() function.

Additional Notes

  • LAST_INSERT_ID() returns the ID of the last inserted row within the current connection, regardless of the table being inserted into.
  • If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() will return the ID of the first row added.
  • Be aware that if you use a trigger to insert rows, the LAST_INSERT_ID() function will return the ID of the last inserted row in the trigger's context, not necessarily the row in the original table.

The above is the detailed content of What\'s the MySQL Equivalent of SQL Server\'s SCOPE_IDENTITY()?. 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