SQL Server identity: IDENTITY_INSERT, SCOPE_IDENTITY, gaps

A SQL Server identity column numbers rows from a seed and an increment. What it guarantees, where gaps come from, and how IDENTITY_INSERT and reseeding work.

What is an identity column in SQL Server?

An identity column in SQL Server is a numeric column that SQL Server fills in on every insert: the first row gets the seed, and each row after it gets the last value plus the increment. You declare it with the IDENTITY property, IDENTITY(seed, increment). Give both or neither; neither means (1, 1).

A small bank, cut down from the bank management system template, numbers its customers from 1 and its accounts from 1000:

CREATE TABLE dbo.Customer (
  CustomerId     int IDENTITY(1, 1) NOT NULL
    CONSTRAINT PK_Customer PRIMARY KEY,
  CustomerNumber varchar(20)   NOT NULL
    CONSTRAINT AK_Customer_CustomerNumber UNIQUE,
  FullName       nvarchar(200) NOT NULL
);
CREATE TABLE dbo.Account (
  AccountId     int IDENTITY(1000, 1) NOT NULL
    CONSTRAINT PK_Account PRIMARY KEY,
  AccountNumber varchar(20) NOT NULL
    CONSTRAINT AK_Account_AccountNumber UNIQUE,
  CustomerId    int         NOT NULL,
  OpenedOn      date        NOT NULL,
  CONSTRAINT FK_Account_Customer_CustomerId
    FOREIGN KEY (CustomerId)
    REFERENCES dbo.Customer (CustomerId)
);
dbo.Customer with primary key CustomerId and alternate key CustomerNumber; dbo.Account with primary key AccountId, alternate key AccountNumber and foreign key CustomerId; a dashed line from Customer to Account.
The seed and increment live in the script; the diagram shows the int keys they fill, with the customer and account numbers kept as alternate keys (AK).

A few rules come with the property, all in CREATE TABLE:

  • It goes on tinyint, smallint, int, bigint, or decimal and numeric with a scale of 0. SQL Server data types gives their ranges and when int runs out.
  • A table has one identity column at most. A second one fails with Msg 2744, “Only one identity column per table is allowed.”
  • An identity column can’t have a default.

CustomerId is a surrogate key: a number the database makes up, with no meaning outside it. The identity property doesn’t make it unique, though. The primary key does that, and AK_Customer_CustomerNumber keeps the bank’s own customer number unique beside it.

What IDENTITY guarantees, and what it doesn’t

Three customers are entered, and the second insert is rolled back:

INSERT INTO dbo.Customer (CustomerNumber, FullName)
VALUES ('C-0001', N'Ana Silva');
BEGIN TRANSACTION;
INSERT INTO dbo.Customer (CustomerNumber, FullName)
VALUES ('C-0002', N'Ben Okafor');
ROLLBACK;
INSERT INTO dbo.Customer (CustomerNumber, FullName)
VALUES ('C-0003', N'Cy Novak');
INSERT INTO dbo.Account (AccountNumber, CustomerId, OpenedOn)
VALUES ('CHK-1000', 1, '2026-03-02');
SELECT CustomerId, CustomerNumber FROM dbo.Customer;
SELECT AccountId, AccountNumber FROM dbo.Account;

Ana gets 1 and Cy gets 3. The rolled-back insert took 2, and SQL Server doesn’t hand it out again. The first account is 1000, the seed.

Microsoft lists what the property doesn’t guarantee:

  • Unique values: only a primary key, a unique constraint or a unique index enforces that.
  • Consecutive values within a transaction: concurrent inserts can take numbers in between.
  • Consecutive values after a restart or a failover: SQL Server caches identity values, and the cached ones are lost. The database option IDENTITY_CACHE = OFF avoids those gaps at some cost to insert speed.
  • Reuse: a failed or rolled-back insert burns its number.

What it does guarantee is that each value comes from the current seed and increment, and that concurrent transactions get different values. So treat an identity value as a name for a row, never as a count or a gapless series, and never type one you expect: the INSERT statement conflicted with the FOREIGN KEY constraint shows a loan that named the member a failed insert skipped. A number that must have no gaps needs its own table holding the current value, as Microsoft suggests, or a sequence created with NO CACHE, which still loses the numbers of transactions that roll back.

How to insert a value into an identity column

Ben’s row didn’t make it, and the branch wants him back as customer 2. Give CustomerId a value and SQL Server refuses:

INSERT INTO dbo.Customer (CustomerId, CustomerNumber, FullName)
VALUES (2, 'C-0002', N'Ben Okafor');
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'Customer' when IDENTITY_INSERT is set to OFF.

An identity insert in SQL Server takes SET IDENTITY_INSERT on the table, and an insert that lists its columns. Here it also loads Dee, customer 500 in the system the bank is moving from:

SET IDENTITY_INSERT dbo.Customer ON;
INSERT INTO dbo.Customer (CustomerId, CustomerNumber, FullName)
VALUES (2, 'C-0002', N'Ben Okafor'),
       (500, 'C-0500', N'Dee Moreau');
SET IDENTITY_INSERT dbo.Customer OFF;
INSERT INTO dbo.Customer (CustomerNumber, FullName)
VALUES ('C-0004', N'Eli Grant');
SELECT CustomerId, CustomerNumber FROM dbo.Customer;

Ben fills the gap at 2. Eli, inserted after the setting is off again, gets 501: an explicit value above the current identity becomes the current identity. Load old rows this way and the new ones carry on after them.

The setting holds for one table per session. Turning it on for dbo.Account while dbo.Customer still has it fails with Msg 8107, “IDENTITY_INSERT is already ON for table ‘Bank.dbo.Customer’”. It also needs ownership of the table or ALTER permission on it, which most application logins shouldn’t have, so keep it to migration scripts and switch it off at their end.

SCOPE_IDENTITY vs @@IDENTITY vs IDENT_CURRENT

After an insert, the application usually needs the new key, to write the rows that point at it. The bank logs every new account in a table with an identity of its own:

CREATE TABLE dbo.AccountEvent (
  AccountEventId int IDENTITY(1, 1) NOT NULL
    CONSTRAINT PK_AccountEvent PRIMARY KEY,
  AccountId      int          NOT NULL,
  EventType      varchar(20)  NOT NULL,
  LoggedAt       datetime2(0) NOT NULL
    CONSTRAINT DF_AccountEvent_LoggedAt
      DEFAULT (SYSUTCDATETIME()),
  CONSTRAINT FK_AccountEvent_Account_AccountId
    FOREIGN KEY (AccountId) REFERENCES dbo.Account (AccountId)
);
dbo.Customer, dbo.Account and dbo.AccountEvent, with primary key AccountEventId and foreign key AccountId; dashed lines from Customer to Account and from Account to AccountEvent.
dbo.AccountEvent's identity starts at 1. The trigger that fills it is in the next script; triggers aren't drawn.

A trigger writes that log row:

CREATE TRIGGER dbo.TR_Account_Opened ON dbo.Account
AFTER INSERT AS
INSERT INTO dbo.AccountEvent (AccountId, EventType)
SELECT AccountId, 'Opened' FROM inserted;

Now Cy opens a savings account, and the batch asks for the new key three ways:

INSERT INTO dbo.Account (AccountNumber, CustomerId, OpenedOn)
VALUES ('SAV-1001', 3, '2026-03-09');
SELECT SCOPE_IDENTITY() AS ScopeIdentity,
       @@IDENTITY AS LastIdentity,
       IDENT_CURRENT('dbo.Account') AS IdentCurrent;

SCOPE_IDENTITY() returns 1001, the account. @@IDENTITY returns 1, the event row the trigger wrote. IDENT_CURRENT('dbo.Account') returns 1001 too, but only because nobody else was inserting.

The three differ in what they look at, as the SCOPE_IDENTITY docs put it:

  • SCOPE_IDENTITY() gives the last identity value made in this session and this scope, the batch or procedure you are in. A trigger is a scope of its own, so its insert doesn’t count.
  • @@IDENTITY gives the last value made in this session in any scope, the trigger’s included. Code that reads it works until someone adds a trigger.
  • IDENT_CURRENT('table') gives the last value made for that table by any session. Under load, it can be another connection’s row.

Use SCOPE_IDENTITY() right after the insert. After a multi-row insert it returns only the last row’s value; the OUTPUT clause returns every row’s key.

Reset the identity seed with DBCC CHECKIDENT

Dee and Eli were test rows, and they are deleted. The table’s current identity stays at 501, so the next customer would be 502. DBCC CHECKIDENT reports it and sets it:

DELETE FROM dbo.Customer WHERE CustomerId >= 500;
DBCC CHECKIDENT ('dbo.Customer', NORESEED);
DBCC CHECKIDENT ('dbo.Customer', RESEED, 3);
INSERT INTO dbo.Customer (CustomerNumber, FullName)
VALUES ('C-0004', N'Eli Grant');
SELECT CustomerId, CustomerNumber FROM dbo.Customer;
Checking identity information: current identity value '501', current column value '3'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
Checking identity information: current identity value '501'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.

NORESEED only reports: the current identity value is 501, the highest value in the column 3. RESEED, 3 sets it to 3 (its message shows the value it replaced), and because the table has rows, the next insert gets 3 plus the increment. Eli comes back as customer 4. On a table that was just created or emptied with TRUNCATE TABLE, the next insert would get 3 itself.

RESEED without a value is the safe form: it raises the current identity to the column’s highest value when it is below it, and never lowers it. A value below the highest one is where it goes wrong:

DBCC CHECKIDENT ('dbo.Customer', RESEED, 1);
INSERT INTO dbo.Customer (CustomerNumber, FullName)
VALUES ('C-0005', N'Fay Lind');
Checking identity information: current identity value '4'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint 'PK_Customer'. Cannot insert duplicate key in object 'dbo.Customer'. The duplicate key value is (2).
The statement has been terminated.

The next number is 2, and Ben has it. The primary key catches the duplicate here. On an identity column without one, SQL Server would store a second customer 2.

DBCC CHECKIDENT can’t change the seed the table was created with, and it doesn’t renumber existing rows. For either, the column has to be dropped and created again.

An existing column can’t become an identity either. A branch table keyed by a plain int, given ALTER COLUMN BranchId int IDENTITY(1, 1) NOT NULL, fails with Msg 156, “Incorrect syntax near the keyword ‘IDENTITY’.” There are two ways round it. ALTER TABLE dbo.Branch ADD a new identity column, and SQL Server numbers the existing rows, here 1 and 2. Or create the table again as dbo.BranchNew with the identity on BranchId and move the rows into it, with INSERT ... SELECT under IDENTITY_INSERT or with ALTER TABLE dbo.Branch SWITCH TO dbo.BranchNew, which moves them without copying, then drop the old table and rename the new one. After the switch the current identity is NULL; DBCC CHECKIDENT ('dbo.Branch') sets it to 2, and the next branch gets 3.

A SEQUENCE instead of IDENTITY

A sequence is an object of its own, not a column property. A column takes its numbers through a default, so an insert can also give the key itself, with no IDENTITY_INSERT. Here the account transactions take their keys from one:

CREATE SEQUENCE dbo.AccountTransactionIdSeq AS int START WITH 1;
CREATE TABLE dbo.AccountTransaction (
  AccountTransactionId int NOT NULL
    CONSTRAINT DF_AccountTransaction_AccountTransactionId
      DEFAULT (NEXT VALUE FOR dbo.AccountTransactionIdSeq)
    CONSTRAINT PK_AccountTransaction PRIMARY KEY,
  AccountId            int           NOT NULL,
  Amount               decimal(12, 2) NOT NULL,
  PostedAt             datetime2(0)  NOT NULL,
  CONSTRAINT FK_AccountTransaction_Account_AccountId
    FOREIGN KEY (AccountId) REFERENCES dbo.Account (AccountId)
);
dbo.Customer and dbo.Account as before; dbo.AccountTransaction with primary key AccountTransactionId and foreign key AccountId; dashed lines from Customer to Account and from Account to AccountTransaction.
The sequence and the default that reads it are in the script; the diagram shows the int key they fill.

Two old transactions come over from the previous system with their own numbers, 1 and 2. Then a new deposit takes its key from the sequence:

INSERT INTO dbo.AccountTransaction
  (AccountTransactionId, AccountId, Amount, PostedAt)
VALUES (1, 1000, 250.00, '2026-03-02 09:00'),
       (2, 1000, -40.00, '2026-03-03 12:30');
INSERT INTO dbo.AccountTransaction (AccountId, Amount, PostedAt)
VALUES (1001, 100.00, '2026-03-09 10:15');
ALTER SEQUENCE dbo.AccountTransactionIdSeq RESTART WITH 3;
INSERT INTO dbo.AccountTransaction (AccountId, Amount, PostedAt)
VALUES (1001, 100.00, '2026-03-09 10:15');
SELECT AccountTransactionId, AccountId, Amount
FROM dbo.AccountTransaction;
Msg 2627, Level 14, State 1, Line 5
Violation of PRIMARY KEY constraint 'PK_AccountTransaction'. Cannot insert duplicate key in object 'dbo.AccountTransaction'. The duplicate key value is (1).
The statement has been terminated.

The sequence hands out 1, which is taken. Unlike the identity that moved past Dee’s 500, a sequence doesn’t notice what was inserted around it; ALTER SEQUENCE ... RESTART WITH 3 moves it, and the retry gets 3. Set against IDENTITY:

  • A sequence gives the number before the insert (NEXT VALUE FOR into a variable), shares one series between tables, and its increment can be changed.
  • It leaves uniqueness to the primary key and keeps no watch over explicit values, so a load needs a restart after it.
  • Its numbers have gaps for the same reasons as identity: a value is used up when it is asked for, inserted or not.

For one table that only needs a number per row, IDENTITY is less to manage.

How ERDsmith helps

Which column is the identity, its type and its seed get fixed by the CREATE TABLE. After that, the property can’t be added to a column or taken off one, and a new seed means dropping the column and adding it again. In ERDsmith it stays a checkbox in the column panel while you design:

  • A table’s first key column, added in its key area, starts as an int identity, named by the project’s key column template.
  • A new identity is (1, 1) and NOT NULL; the column panel shows its seed and increment.
  • Make another column the identity and the first one gives it up, with a line in the Output saying so: a table never reaches Msg 2744.
  • An identity on a type SQL Server refuses, or with a default, marks its table in the model tree and is reported in the Output, as Msg 2749 and Msg 1754 would report it.