How to Turn IDENTITY_INSERT On and Off Using SQL Server?
Last Updated :
02 Feb, 2024
IDENTITY_INSERT in SQL Server is a valuable tool in SQL Server 2008, allowing us to control how identity values are assigned when inserting new records into a table. IDENTITY_INSERT
ON
is a Transact-SQL statement that allows us to explicitly specify the value we want to insert into the identity column of a table.
In this article, we will understand How to turn IDENTITY_INSERT on and off using SQL Server 2008 with multiple examples and so on.
Introduction to IDENTITY_INSERT in SQL Server
The identity column is the numeric column in the SQL Server table whose value increments automatically. The value of the identity column is set by the SQL Server itself based on the definition provided by the user. Thus user can not explicitly set the value of such columns and they are unique. The identity column can not be NULL.
Syntax:
IDENTITY [( seed, increment)]
Explanation: Here, seed means the first value to start with while loading the data into the table and increment is the value added to the previous identity value of the column.
Examples of How to Turn IDENTITY_INSERT On and Off Using SQL Server
Example 1: Create a Table With an Identity Column and See it Functions
Let's Create a database named "GeeksForGeeks" with a table named "students" to store student records. The table should include columns for student ID, first name, last name, and mentor. We will also Insert sample student records into the table.
Query:
USE GeeksForGeeks
CREATE TABLE students
(Id int identity(1,1), FirstName varchar(50), LastName varchar(150), Mentor varchar(50))
INSERT INTO students values
('Raman', 'Raghuvanshi', 'Namita Thapar'),
('Raghav', 'Jain', 'Swati Pathak'),
('Jolly', 'Modi', 'Prerna Patil'),
('Shubham', 'Sambal', 'Rohit Raina')
SELECT * FROM students
Output:
In output window, we can see Id column data is insertedExplanation: We have created identity column with seed value 1 and incremented it with 1, and you must notice that while inserting the data, Id column is not mentioned and it output table we can see its value as SQL Server automatically inserts data based on seed and increment value. If we change the seed value to 100 and increment to 2, then values of the Id column will be 100, 102, 104, etc.
What if we tried to include the Id column while inserting the data in the table.
Example 2: Try to Insert Explicit Value for Id Column
Let's Write a query to insert a new student record into the "students" table with the given details: FirstName - 'Raman', LastName - 'Raghuvanshi', Mentor - 'Namita Thapar'. We will ensure the "Id" column, an identity column, is automatically generated by the database.
Query:
INSERT INTO students values
(1, 'Raman', 'Raghuvanshi', 'Namita Thapar')
Output:
We get the errorExplanation: The error says we can not insert the explicit value in the table where identity on the column is defined. And it even suggests us the way to do it by using the IDENTITY_INSERT property.
So, now let's solve our issue by using the IDENTITY_INSERT property.
How to Turn IDENTITY_INSERT ON SQL Server 2008
IDENTITY_INSERT ON
statement that allows us to explicitly specify the value we want to insert into the identity column of a table, instead of depend on the database to automatically generate the next value in the sequence.
Syntax:
SET IDENTITY_INSERT [ [ database_name.] schema_name.] table_name { ON }
Explanation: Values mentioned in square brackets are optional. This syntax is applicable to SQL Server 2000 and later versions. So it covers SQL Server 2008.
Example 1: Insert Explicit Value by Set IDENTITY_INSERT to ON
Let's consider the situation where we have to insert the students data having id = 10 for some reason. We can not insert the row data directly like this, so in order to insert explicit value we need to set IDENTITY_INSERT to ON.
Query:
SET IDENTITY_INSERT students ON
INSERT INTO students
(ID, FirstName, LastName, Mentor)
values
(10, 'Piyush','Goyal', 'Virat Gupta'),
(20, 'Pankaj','Varma', 'Prakash Jha'),
(30, 'Sadhana','Chavhan', 'Swapnil Patil')
SELECT * FROM students
Output:
We got the success to insert the explicit values into our table by setting IDENTITY_INSERT to ON Explanation: We have set IDENTITY_INSERT value of the table students to ON and then inserted the data and notice that we have mentioned the columns list this time and it was not mentioned in the above 2 examples, so whenever we are using identity insert we have to mention the identity columns in the column list and then we can insert whatever value we want to insert even if it is duplicate as identity column does not is not unique unless provided in the definition.
Example 2: Get Back to out Routine Where SQL Server Automatically Insert Values in Id Column
Let's Insert a new record into the "students" table with the values 'Madhura' for FirstName, 'Sharma' for LastName, and 'Satish Kumar' for Mentor. Ensure that the identity column "ID" is automatically incremented.
Query:
INSERT INTO students values
('Madhura', 'Sharma', 'Satish Kumar')
Output:
We got the error again.Explanation: We faced the error while insert the data normally just like used in example 1, because we have set identity insert to on. So when we want to insert data as per identity definition of seed and increment we have to set the identity insert value to off. We can not set to OFF unless it is already ON.
How to Turn IDENTITY_INSERT OFF SQL Server 2008
IDENTITY_INSERT OFF
is the default state for a table's identity column. It signifies that automatic identity value generation is enabled, meaning the database assigns the next sequential value whenever we insert a new row without specifying a value for the identity column.
Syntax:
SET IDENTITY_INSERT [ [ database_name.] schema_name.] table_name { OFF }
Explanation: This syntax is applicable to SQL Server 2000 and later versions. So it covers SQL Server 2008
Example 1: Let's Solve Above Error and Set Identity Insert to OFF.
Let's Insert a new record into the "students" table with the values 'Madhura' for FirstName, 'Sharma' for LastName, and 'Satish Kumar' for Mentor. Ensure that the identity column "ID" is automatically incremented, and turn off the IDENTITY_INSERT option after the insertion.
Query:
SET IDENTITY_INSERT students OFF
INSERT INTO students values
('Madhura', 'Sharma', 'Satish Kumar')
SELECT * FROM students
Output:
Toda! Issue resolved and we inserted the value in the tableExplanation: We resolved above error by setting IDENTITY_INSERT of students table to OFF which informs SQL Server to function normally as per definition of the identity column. We can see that Id of the row 8 which is the latest data inserted in 31 because SQL Server increments the value based on previous value of the column.
So for the best practice, whenever it is required to insert explicit values in the identity column set the IDENTITY_INSERT to ON and once insertion is done set IDENTITY_INSERT to OFF.
Conclusion
In summary, we have understood the core concept of the identity column in SQL Server and the significance of Identity Insert option between ON and OFF. The identity column streamlines the generation of unique values, simplifying the management of primary keys. Turning Identity Insert ON allows for explicit value insertion, beneficial in scenarios like data imports or migrations. Conversely, setting it to OFF maintains automatic generation, ensuring data integrity.
Similar Reads
How to Get the Identity of an Inserted Row in SQL Server
In SQL Server, we can use an Identity column, which will automatically increment the ID value in a table. The Identity column is a unique, sequential, and non-null value for each row in a table. The identity value is auto-incremented using the IDENTITY command. There could be situations when this au
4 min read
How to Install and Use MS SQL Server on Linux?
Microsoft SQL Server is a relational database management system (RDBMS) that supports a broad range of transaction processing, business intelligence, and analytics applications. Along with Oracle Database and IBM's DB2, Microsoft SQL Server is one of the three market-leading database technologies. M
4 min read
How to Get the Identity of an Inserted Row in SQL
In databases, Sometimes we need the identity of an inserted row in SQL. The identity value of the newly inserted row is very useful for various purposes in the database. In SQL, the RETURNING INTO clause within an INSERT statement enables retrieval of the inserted row's identity. When working with S
4 min read
How to Install SQL Server Agent on Windows?
SQL Server Agent is a component of Microsoft SQL Server. It schedules jobs and handles other automated task on a database.This windows service can automatically start when we boot up the system or set it up manually. SQL Server Agent enables us to automate all the task which are repetitive in nature
3 min read
How to install SQL Server Agent on Linux?
SQL Server Agent is a Microsoft Windows service that runs SQL Server jobs, which are scheduled administration activities. SQL Server Agent stores job information in SQL Server. One or more job steps can be found in a job. Each phase has its own set of tasks, such as backing up a database. Installing
2 min read
How to Insert If Not Exists in SQL SERVER?
Adding Data to a table in SQL Server is a key operation. Data can be inserted into tables using many different scenarios like plain data inserted into a table without checking anything or checking if data already exists in the target table and only if the data does not exist then the new data is ins
7 min read
How To Reset Identity Column Values In SQL
An Identity Column in SQL is an auto-incrementing column used to generate unique values for each row inserted into a table. This feature is commonly used in tables that require a unique identifier, such as primary keys. The identity column allows the database to automatically handle the generation o
5 min read
How to Install SQL Server Client on Windows?
The Client / Server Application is a computer program that allows users to access what is stored on the server. Of course, both computers can be workstations running the same type of operating system. In most network environments, the server contains a database that requires users to access this dat
2 min read
What is Identity Theft? How to Prevent It, Warning Signs and Tips
Identity theft is when someone steals your personal information and uses it for financial or other fraudulent purposes without your permission. This information theft can include your name, social security number, credit card information, or other sensitive information. Once thieves have access to t
13 min read
How to Add an IDENTITY to an Existing Column in SQL Server
It enables you to store, organize, and manipulate data in a relational format, meaning data is organized into tables. It Stores and manages data for dynamic web applications, ensuring effective user experiences. In this article, we will learn about How to add an identity to an existing column in SQL
5 min read