Skip to content

Handling identity columns during SQL Server synchronisation

How to synchronise SQL Server tables with identity columns safely: IDENTITY_INSERT, reseeding afterwards, avoiding key collisions when both sides insert, and checks to run.

Identity columns are one of the most common things that trip up table synchronisation. They generate a new number automatically for every inserted row, which is exactly what you want in normal use and exactly what you don't want when copying rows from another database, where you need the target to keep the source's values. Get it wrong and you end up with different IDs on each side, broken foreign keys or, worse, two different rows sharing the same key.

This guide covers how to copy identity values correctly, how to reseed afterwards, how to avoid collisions when both sides insert rows, and what to check.

Keep the source's values with IDENTITY_INSERT

By default SQL Server won't let you insert a value into an identity column. To keep the source's IDs, turn on `IDENTITY_INSERT` for the target table, insert with an explicit column list, then turn it off again:

```sql

SET IDENTITY_INSERT dbo.Customers ON;

INSERT INTO dbo.Customers (CustomerId, Name, Email, CreatedAt)

SELECT s.CustomerId, s.Name, s.Email, s.CreatedAt

FROM staging.Customers s

WHERE NOT EXISTS (SELECT 1 FROM dbo.Customers t WHERE t.CustomerId = s.CustomerId);

SET IDENTITY_INSERT dbo.Customers OFF;

```

A few rules apply:

  • **An explicit column list is required.** `INSERT ... SELECT *` won't work with `IDENTITY_INSERT` on.
  • **Only one table per session** can have `IDENTITY_INSERT` on at a time. Turn it off before moving to the next table.
  • **It needs the right permission.** The user must own the table or have ALTER permission on it.
  • **Updates are different.** You can't update an identity column at all, with or without `IDENTITY_INSERT`. If a key value changes on the source, it has to be handled as a delete and an insert.

Reseed after copying

When you insert explicit values higher than the table's current identity value, SQL Server moves the seed forward automatically. Problems tend to come from the other direction: copying into a table that already had rows, deleting and reloading, or bulk loads that don't behave as expected. After a sync, check the current identity value against the highest key in the table:

```sql

SELECT IDENT_CURRENT(N'dbo.Customers') AS current_identity,

(SELECT MAX(CustomerId) FROM dbo.Customers) AS max_key;

```

If the current identity is lower than the highest key, the next normal insert will try to reuse an existing value and fail with a primary key violation. Fix it with `DBCC CHECKIDENT`:

```sql

DBCC CHECKIDENT (N'dbo.Customers', RESEED);

```

With no new value given, `RESEED` sets the identity to the current maximum value in the column, so the next row gets the next number.

Avoid collisions when both sides insert

The hardest case is when both the source and the target accept new rows during the period you are syncing, for example while two systems run side by side during a migration. Both will hand out the same next numbers, and the two sets of rows will collide. Some ways to prevent it:

  • **Make only one side writable.** By far the simplest: new rows are created on the source only, and the target is read-only for that table until cutover.
  • **Split the ranges.** Reseed the target to a much higher starting value, for example 1,000,000,000, so its new rows can never overlap the source's. Make sure the column's data type has room; an `int` tops out a little over 2.1 billion.
  • **Use different increments.** Odd numbers on one side and even on the other, by seeding at 1 and 2 with an increment of 2. It works, but it is easy to get wrong and confusing later.
  • **Use a different key.** For new designs, a sequence shared across systems, or a `uniqueidentifier`, avoids the problem entirely at the cost of other trade-offs.

Whichever you choose, document it. Range splits and odd/even schemes are invisible in the data, and the next person to touch the tables needs to know.

Handle replication's NOT FOR REPLICATION

Identity columns marked `NOT FOR REPLICATION` behave slightly differently: when replication agents insert rows, the explicit values are kept and the seed isn't advanced. If you build your own sync on tables that are, or once were, replicated, check for this setting in `sys.identity_columns` (`is_not_for_replication`), because it changes when you need to reseed.

Mind foreign keys

Identity values are usually primary keys, and other tables refer to them. That is the main reason to keep the source's values: child rows on the target need to point at the same parent IDs as on the source. Sync parent tables before child tables, using the same IDs, and avoid any approach that lets the target assign new values to rows that already have children.

Validation checks

After each sync of a table with an identity column, check:

  • **Row counts** match between source and target.
  • **Minimum and maximum key values** match.
  • **No duplicate keys** exist on the target.
  • **The current identity value** on the target is at least the highest key in the table.
  • **Child rows** on the target all have a matching parent.

```sql

SELECT COUNT(*) AS rows_total, MIN(CustomerId) AS min_id, MAX(CustomerId) AS max_id,

COUNT(DISTINCT CustomerId) AS distinct_ids, IDENT_CURRENT(N'dbo.Customers') AS current_identity

FROM dbo.Customers;

```

Run it on both sides and compare.

Troubleshooting Scenarios

Inserts fail with "explicit value for the identity column"

IDENTITY_INSERT isn't on for that table in this session, or the insert doesn't list its columns explicitly.

New rows fail with a primary key violation after a sync

The identity seed is behind the highest key. Run DBCC CHECKIDENT with RESEED.

Both systems created rows with the same IDs

Both sides were inserting into the same range. Make one side read-only, or split ranges by reseeding one side well above the other.

IDENTITY_INSERT fails on a second table

Only one table per session can have it on. Turn it off on the first table before moving on.

FAQ

How do I insert values into an identity column?

Turn on SET IDENTITY_INSERT for the table, insert with an explicit column list, then turn it off again.

How do I reset an identity column after copying data?

Run DBCC CHECKIDENT with RESEED, which sets the identity to the current highest value in the column.

Can I update an identity column?

No. Identity values can't be updated; a changed key has to be handled as a delete and an insert.

How do I stop identity collisions when two systems insert rows?

Make only one side writable, or reseed one side to a separate range well above the other.

Why keep the source's identity values when syncing?

So foreign keys in child tables still point at the right parent rows on the target.

Suggested Related Articles