What is SQL LAST_INSERT_ID
LAST_INSERT_ID, also known as
LAST_INSERT_ID(), is a function that returns the last automatically generated value (typically an auto-incremented primary key) that was inserted into an auto-increment column in a table. It is used to obtain the ID of the most recently inserted row in a table, especially when dealing with tables that have auto-incrementing primary keys.
When you would use it
You would use SQL
LAST_INSERT_ID when you want to:
Retrieve the ID of the last inserted row: Obtain the primary key value of the most recently inserted row, which is often useful for further operations or for tracking relationships with other tables.
Link related records: Use the last inserted ID to establish relationships between tables when inserting data into multiple related tables.
Ensure data consistency: Ensure that data inserted into related tables corresponds correctly by using the last inserted ID.
Implement multi-step transactions: Perform complex operations that require multiple inserts and updates while maintaining data integrity.
Return the ID to an application: When working with applications, you can use the
LAST_INSERT_IDfunction to return the newly generated ID for user feedback or to navigate to a new record.
The basic syntax for SQL
LAST_INSERT_ID varies slightly depending on the database system:
In MySQL and MariaDB:
In SQL Server:
In Oracle Database:
SELECT your_sequence_name.CURRVAL FROM DUAL;
- The syntax for retrieving the last inserted ID is typically a simple function call with empty parentheses.
- Some database systems may require you to specify the sequence or identity column explicitly if there are multiple columns with auto-increment behavior.
Suppose you have a table called "users" with an auto-incremented "user_id" column, and you want to retrieve the ID of the last inserted user. You can use the following SQL query:
SELECT LAST_INSERT_ID() AS last_user_id;
Example table response
Assuming that you've just inserted a new user into the "users" table, the query mentioned earlier would return a result like this:
| last_user_id |
| ----------- |
| 42 |
This result indicates that the last inserted user has an ID of 42.
- Managing relationships between tables with auto-incrementing primary keys.
- Ensuring data consistency when inserting related records.
- Performing multi-step transactions that require knowledge of the last inserted ID.
- Returning the ID to an application for further processing or user feedback.
SQL languages this is available for
LAST_INSERT_ID is available in various relational database management systems (RDBMS) such as:
- SQL Server (as
- PostgreSQL (as
- Oracle Database (using sequences)
Please note that the exact syntax and behavior may vary between different database systems, so it's essential to consult the documentation for your specific database system for precise details.