Why are there gaps in my IDENTITY column values?
Solution 1:
The identity property on a column does not guarantee the following:
Uniqueness of the value – Uniqueness must be enforced by using a PRIMARY KEY or UNIQUE constraint or UNIQUE index.
Consecutive values within a transaction – A transaction inserting multiple rows is not guaranteed to get consecutive values for the rows because other concurrent inserts might occur on the table. If values must be consecutive then the transaction should use an exclusive lock on the table or use the SERIALIZABLE isolation level.
Consecutive values after server restart or other failures –SQL Server might cache identity values for performance reasons and some of the assigned values can be lost during a database failure or server restart. This can result in gaps in the identity value upon insert. If gaps are not acceptable then the application should use a sequence generator with the NOCACHE option or use their own mechanism to generate key values.
Reuse of values – For a given identity property with specific seed/increment, the identity values are not reused by the engine. If a particular insert statement fails or if the insert statement is rolled back then the consumed identity values are lost and will not be generated again. This can result in gaps when the subsequent identity values are generated.
Also,
If an identity column exists for a table with frequent deletions, gaps can occur between identity values. If this is a concern, do not use the IDENTITY property. However, to make sure that no gaps have been created or to fill an existing gap, evaluate the existing identity values before explicitly entering one with SET IDENTITY_INSERT ON
.
Also, Check the Identity Column Properties & check the Identity Increment value. Its should be 1.
Solution 2:
Do not expect the identities to be consecutive. There are many scenarios that can leave gaps. Consider the identity like an abstract number and do not attach any business meaning to it.
Solution 3:
Gaps occur when:
- records are deleted.
- error has occurred when attempting to insert a new record (e.g. not-null constraint error).the identity value is helplessly skipped.
- somebody has inserted/updated it with explicit value (e.g. identity_insert option).
- incremental value is more than 1.
Solution 4:
You can avoid this error either by evaluating the expected error before executing the increment statement, Or by using transaction so that statement is never executed and rolled back if there is any error. Hope it helps