How To Insert Values Into Table With Identity Column In SQL Server

By default, the SQL server won’t allow you to explicitly insert a value for an identity column. But I was surprised to see a requirement that I got from my client. There is no need to insert an explicit value for the identity column as it is auto-generated and auto-incremented. You just need to provide the explicit values for all other columns except the Identity column in your INSERT statement.

To insert data into the table with an identity column in SQL Server, you just need to set the IDENTITY_INSERT to ON and then run the insert query.

If you try to insert an explicit value for an identity column in the SQL server, you will receive the error below. Check out the screenshot below for your reference.

Cannot insert explicit value for identity column in table 'Orders' when IDENTITY_INSERT is set to OFF.

This error occurs because IDENTITY_INSERT is set to OFF by default for the table that contains the identity column. Therefore, explicit values for the identity column are not allowed.

If you still need to insert an explicit value for the Identity column, follow the below steps.

Check out: An explicit value for the identity column in table

Before inserting the query, run the query below to set the IDENTITY_INSERT to ON. Check out the screenshot below for your reference.

SET IDENTITY_INSERT Orders ON;
how to insert values into table with identity column in sql server

Now, let’s run the Insert query below. You will see that the record has been inserted successfully.

INSERT INTO Orders (OrderID, OrderName, OrderType) VALUES (3,'Medicine', 'Health');
How to insert values into table with identity column in SQL Server

To cross-check if the Record has been inserted successfully, Let’s run the Select statement below. The screenshot below shows that the record has been inserted successfully.

Check out: How To Add Identity Column To Existing Table In SQL Server

Select * from Orders
How to insert values in identity column in SQL server

Now, you can turn off the explicit insertion into the table with the identity column with the below query.

SET IDENTITY_INSERT Orders OFF;
insert values in identity column in sql server

Conclusion

Ideally, it is not a good idea to insert an explicit value for an identity column in an SQL server as it is an autogenerated column. But if you have a requirement, you can use the above information to insert an explicit value for an identity column in a table.

You may also like following the articles below

Leave a Comment