How do I retrieve the ID of an inserted row in SQL?
Column | Type
--------|--------------------------------
ID | * Auto-incrementing primary key
Name |
Age |
insert into users (Name, Age) values ('charuka',12)
In SQL Server, you can do (in addition to the other solutions already present):
INSERT INTO dbo.Users(Name, Age)
OUTPUT INSERTED.ID AS 'New User ID'
VALUES('charuka', 12)
The OUTPUT
clause is very handy when doing inserts, updates, deletes, and you can return any of the columns - not just the auto-incremented ID
column.
Read more about the OUTPUT clause in the SQL Server Books Online.
In MySQL:
SELECT LAST_INSERT_ID();
In SQL Server:
SELECT SCOPE_IDENTITY();
In Oracle:
SELECT SEQNAME.CURRVAL FROM DUAL;
In PostgreSQL:
SELECT lastval();
(edited: lastval is any, currval requires a named sequence) Note: lastval() returns the latest sequence value assigned by your session, independently of what is happening in other sessions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With