To use IDENTITY_INSERT = ON in a SQL Server script, you’re enabling the ability to explicitly insert values into a table’s identity column (which normally auto-generates values). Here’s how to do it properly:
| |
Now, you need to understand some important rules:
- Only one table in a session can have
IDENTITY_INSERTset toONat a time. - You must include the identity column in the
INSERTstatement. - The value you insert must not conflict with existing values in the identity column.
So, let’s suppose you have a table called Employees:
| |
To insert a specific EmployeeID:
| |
A Few Extra Interesting Facts
I learned some interesting points when I dug the topic into more detail.
First, the value doesn’t strictly have to avoid conflicts in all cases—a duplicate only fails if a unique constraint/PK exists (which is the usual case). What the docs specifically note is: if the value inserted is larger than the current identity value for the table, SQL Server automatically uses the newly inserted value as the current identity value.
And second, the user must own the table or have ALTER permission on the table.
Documentation
The official Microsoft documentation is:
SET IDENTITY_INSERT (Transact-SQL)—https://learn.microsoft.com/en-us/sql/t-sql/statements/set-identity-insert-transact-sql
It applies to SQL Server, Azure SQL Database, Azure SQL Managed Instance, Azure Synapse Analytics, and SQL database in Microsoft Fabric.
If you want a specific product version, append the view parameter to the URL (e.g., ?view=sql-server-ver17 for the latest, or `?view=sql-server-ver16’).
Follow me
Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.
Photo by Microsoft Server
