Home >Database >Mysql Tutorial >How to Retrieve the Last Auto-Incremented ID in MySQL?

How to Retrieve the Last Auto-Incremented ID in MySQL?

Barbara Streisand
Barbara StreisandOriginal
2024-11-24 03:21:08309browse

How to Retrieve the Last Auto-Incremented ID in MySQL?

Retrieving Auto-Incremented Value: MySQL Equivalent of SCOPE_IDENTITY

In SQL Server, the SCOPE_IDENTITY() function retrieves the last auto-incremented value generated by an INSERT statement. MySQL provides a similar function called LAST_INSERT_ID() to achieve this functionality.

MySQL LAST_INSERT_ID() Function

The LAST_INSERT_ID() function returns the last auto-incremented value generated for the current session, regardless of the table or database where it occurred.

Usage:

SELECT LAST_INSERT_ID();

This returns a single integer representing the last auto-incremented value.

Example:

INSERT INTO Table1 (Name) VALUES ('John');
SELECT LAST_INSERT_ID();

This would return the auto-incremented ID assigned to the newly inserted row in Table1.

Note:

LAST_INSERT_ID() operates on a session-specific basis. This means that if you have multiple database connections, each session will retrieve its own last auto-incremented value.

In Case of Triggers:

LAST_INSERT_ID() retrieves the value of the last inserted row in the current table, even if it was inserted as a result of a trigger.

The above is the detailed content of How to Retrieve the Last Auto-Incremented ID 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