Identity Insert On SQL

Galaxy Glossary

How do you temporarily allow inserting values into an identity column?

The `IDENTITY_INSERT` command in SQL Server allows you to manually insert values into an identity column. This is useful for importing data or for specific scenarios where you need to control the identity seed. It's crucial to understand that this is a temporary change.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The `IDENTITY_INSERT` command in SQL Server is a DDL command that temporarily disables the automatic generation of identity values for a specified table. This allows you to explicitly set the values for the identity column during an INSERT statement. This is often used when importing data from external sources or when you need to control the sequence of identity values. It's important to note that `IDENTITY_INSERT` is a table-level operation, meaning it affects all rows inserted into the table until you turn it off. This is different from setting the `IDENTITY_SEED` or `IDENTITY_INCREMENT` which are specific to the table and column. Using `IDENTITY_INSERT` is a powerful tool, but it's crucial to understand its temporary nature and the potential for data integrity issues if not used carefully.

Why Identity Insert On SQL is important

Understanding `IDENTITY_INSERT` is crucial for data migration and import tasks. It allows you to maintain control over identity values when dealing with external data sources or specific application requirements. This avoids potential conflicts or errors during data loading.

Example Usage


-- Enable IDENTITY_INSERT for the 'Customers' table
SET IDENTITY_INSERT Customers ON;

-- Insert a new customer with a specific identity value
INSERT INTO Customers (CustomerID, FirstName, LastName)
VALUES (1001, 'John', 'Doe');

-- Insert another customer
INSERT INTO Customers (CustomerID, FirstName, LastName)
VALUES (1002, 'Jane', 'Smith');

-- Disable IDENTITY_INSERT for the 'Customers' table
SET IDENTITY_INSERT Customers OFF;

-- Verify the identity column is working as expected
INSERT INTO Customers (FirstName, LastName)
VALUES ('Peter', 'Jones');

SELECT * FROM Customers;

Common Mistakes

Want to learn about other SQL terms?