4 ways to get identity IDs of inserted rows in SQL Server
In this post I’ll explain the 4 methods available to get the IDs of newly inserted rows when the table has an identity Id column.
@@IDENTITY
This variable contains the last identity value generated by the current connection, is not limited to the scope of the code being executed. In case the current connection didn’t insert any row with an identity the property will have a NULL value.
This code will give you unexpected result if there is a trigger, running for inserts in TableA, that is inserting row in other tables with an identity. In this case the @@IDENTITY variable will give you the ID inserted by the trigger, not the one inserted in the current scope.
2) SCOPE_IDENTITY()
This function will return the value of the last identity inserted in the current executing batch.
The following code
will return the last value inserted in TableA by our insert, even if other connections, or trigger fired by the current connection are inserting values with IDs.
This will be the best method to use in most of the cases.
3) IDENT_CURRENT(‘table’)
This function returns the last identity value inserted in the specified table, regardless of the scope and connection.
This function is available in SQL Server 2005 and newer versions.
4) OUTPUT
The output clause can be used to get IDs when inserting multiple rows.
This obviously will insert into @NewIds the Ids generated by the current statement. Other connection or code executing in different scopes will not affect the result of the operation.
Like IDENT_CURRENT , also this function is available in SQL Server 2005 and newer versions.
SQL: How to get the id of values I just INSERTed?
I inserted some values into a table. There is a column whose value is auto-generated. In the next statement of my code, I want to retrieve this value.
Can you tell me how to do it the right way?
![]()
![]()
21 Answers 21
@@IDENTITY is not scope safe and will get you back the id from another table if you have an insert trigger on the original table, always use SCOPE_IDENTITY()
This is how I do my store procedures for MSSQL with an autogenerated ID.
This works very nicely in SQL 2005:
It has the benefit of returning all the IDs if your INSERT statement inserts multiple rows.
If your using PHP and MySQL you can use the mysql_insert_id() function which will tell you the ID of item you Just instered.
But without your Language and DBMS I’m just shooting in the dark here.
Again no language agnostic response, but in Java it goes like this:
If you are working with Oracle:
Inset into Table (Fields. ) values (Values. ) RETURNING (List of Fields. ) INTO (variables. )
INSERT INTO PERSON (NAME) VALUES (‘JACK’) RETURNING ID_PERSON INTO vIdPerson
or if you are calling from. Java with a CallableStatement (sry, it’s my field)
INSERT INTO PERSON (NAME) VALUES (‘JACK’) RETURNING ID_PERSON INTO ?
and declaring an autput parameter for the statement
There’s no standard way to do it (just as there is no standard way to create auto-incrementing IDs). Here are two ways to do it in PostgreSQL. Assume this is your table:
You can do it in two statements as long as they’re consecutive statements in the same connection (this will be safe in PHP with connection pooling because PHP doesn’t give the connection back to the pool until your script is done):
lastval() gives you the last auto-generated sequence value used in the current connection.
The other way is to use PostgreSQL’s RETURNING clause on the INSERT statement:
This form returns a result set just like a SELECT statement, and is also handy for returning any kind of calculated default value.
An important note is that using vendor SQL queries to retrieve the last inserted ID are safe to use without fearing about concurrent connections.
I always thought that you had to create a transaction in order to INSERT a line and then SELECT the last inserted ID in order to avoid retrieving an ID inserted by another client.
But these vendor specific queries always retrieve the last inserted ID for the current connection to the database. It means that the last inserted ID cannot be affected by other client insertions as long as they use their own database connection.
Assuming the following table definition:
You can use the following:
Which will return the value of the ID column.
From the site i found out the following things:
SELECT @@IDENTITY It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value. @@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.
SELECT SCOPE_IDENTITY() It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.
SELECT IDENT_CURRENT(‘tablename’) It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.
Как взять id будущей записи?

Для получения следующего значения автоинкрементируемого поля можно использовать запрос:
Но как совершенно верно заметил коллега Александр — идея абсолютно идиотская.
- Вконтакте

- Вконтакте

- Вконтакте


Egorr, Да, я активно использую эту библиотеку в связке с Doctrine.
Вот пример сущности, использующей Uuid:
Итого, при создании экземпляра класса мы уже имеем автоматически сгенерированный уникальный Id. Можно также задействовать валидатор и бросить исключение, если вдруг! был сгенерирован уже существующий идентификатор.


Egorr, Ну, если говорить о производительности, то на мой взгляд, это актуально лишь на действительно больших объёмах одновременных операций (например, как описано тут — it takes 20 minutes to insert 100,000 records into a UUID table which already contains 15 million records).
В таких случаях да, вероятно, нужно искать другое решение. Вот вариант с PostgreSQL/Sequence.
По большей части, при решении бизнес задач, если запрос выполняется неприлично долго, практически всегда есть возможность закешировать его результаты, если, к примеру, это какой-нибудь список товаров. Ну а если это аналитический отчёт — то, думаю, не будет большой разницы в том, 30 секунд он формируется или 50.
4 ways to get last inserted id of a MySQL table
This article will see how to get the last inserted id of a MySQL table using 4 different ways.
Table of Contents
Let us get started by preparing the sample data. We will be creating a table, employee_designation, followed by inserting rows into it.
Note that the id column is missing in the insert statements as id is an auto_increment key and will assign the non-negative values on its own.
Action Output:-
Frequently Asked:
Create table and inserts are successful, to view the snapshot of the table execute:
Output:-
How to get last inserted id of a MySQL table using max() function
We will be using the max() function to get the last inserted id. Max() function returns the maximum value at present for a particular column. Observe the below query for the solution:
Output:-
The output in image_3 shows that the last inserted id was 7 in the employee_designation table.
How to get last inserted id of a MySQL table using ORDER BY DESC
We will be doing ORDER BY DESC on the returned id values from a select query to get the last inserted id. The query will first select all the values from the id column followed by ordering them in descending order. Finally, only one record is returned as a LIMIT clause is applied. Observe the below query for the solution:
Output:-
The output in image_4 shows that the last inserted id was 7 in the employee_designation table.
How to get last inserted id of a MySQL table using LAST_INSERT_ID()
We will be using the LAST_INSERT_ID() function to get the last inserted id. Last_insert_id() MySQL function returns the BIG UNSIGNED value for an insert statement on an auto_increment column.
Important Note:
If there is only a single insert statement for multiple rows, last_insert_id() will return the value generated only for the first inserted row.
Observe the below query for the solution.
Output:-
How to get last inserted id of a MySQL table using AUTO_INCREMENT
We will be using the INFORMATION SCHEMA to get the last inserted id of an auto-incremented column of a MySQL table.
Important Note:
Note that the below solution will work only for the columns with auto_increment.
Observe the below query for the solution.
Output:-
READ MORE:
We hope this article helped you to get the last inserted id from a MySQL table. Good Luck.
Related posts:
1 thought on “4 ways to get last inserted id of a MySQL table”
Hello, thank you for this! But isn’t AUTO_INCREMENT the next value to be used as an ID (in this case 8), instead of the last one?
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.