Skip to content

SELECT @@IDENTITY

Returns the last AutoNumber value generated on the connection, or the number of rows the last data statement affected.

Access SQL. SELECT @@IDENTITY is ACE’s own: the Jet provider (EFCore.Jet) sends it to ACE as written. @@ROWCOUNT is a different case: the Jet provider answers SELECT @@ROWCOUNT itself rather than sending it to ACE. LibRed answers both.

SELECT { @@IDENTITY | @@ROWCOUNT } [ [ AS ] alias ] [ , … ]

A system variable can also stand anywhere an expression can in an ordinary query:

SELECT … @@IDENTITY … FROM …

The last AutoNumber value generated on this connection, by any table. Null if the connection has generated none. After a statement that inserts several rows, it is the last row’s value. After an insert with IN external_database, it is the other file’s new AutoNumber.

The number of rows the last INSERT, UPDATE or DELETE on this connection affected. 0 if there has been none. A SELECT leaves it unchanged.

A name for the output column. Without one, the column is named IDENTITY or ROWCOUNT.

The form without FROM accepts only system variables. An ordinary SELECT needs a FROM, and returns the variable’s value on every row.

Both variables belong to the connection. Read them on the connection that ran the statement, either in a later command or in the same batch: INSERT INTO … ; SELECT @@IDENTITY. EF Core reads a new key back this way.

@@IDENTITY keeps its value through statements that generate no AutoNumber, such as an UPDATE or a DELETE.

LibRed has no other system variables. Any other @@ name, such as @@VERSION, fails with “Unknown system variable”.

These run against the Northwind sample database. They follow on from each other, and must run on one connection, since the variables belong to the connection.

CREATE TABLE Tickets (Id COUNTER PRIMARY KEY, Subject TEXT(255))
INSERT INTO Tickets (Subject) VALUES ('first')

Read the new Id and the row count; both are 1:

SELECT @@IDENTITY, @@ROWCOUNT

Insert two rows, then read the last Id (3) and the count (2) under names of your own:

INSERT INTO Tickets (Subject) VALUES ('second'), ('third')
SELECT @@IDENTITY AS LastId, @@ROWCOUNT AS Added

Use the variable in a query to fetch the row just added:

SELECT Id, Subject FROM Tickets WHERE Id = @@IDENTITY

Insert and read the new key in one batch:

INSERT INTO Tickets (Subject) VALUES ('fourth'); SELECT @@IDENTITY