SQL > Advanced SQL > IDENTITY

IDENTITY is used in Microsoft SQL Server to automatically insert numerical primary key values to a table as new data is inserted. This is similar to the AUTO INCREMENT command in MySQL.

SQL Server's IDENTITY property automatically generates sequential numeric primary key values when rows are inserted, eliminating the need to manually specify key values and ensuring uniqueness.

Syntax

The syntax for IDENTITY is as follows:

CREATE TABLE TABLE_NAME
(PRIMARY_KEY_COLUMN INT PRIMARY KEY IDENTITY ( [Initial_Value], [Interval] ),
...);

where [Initial_Value] is the first value of the primary key, and [Interval] is the interval between two consecutive identity values. If no [Initial_Value] or [Interval] is specified, the default for both is 1. In other words, the primary key for the first row would be 1, and subsequent rows would get a primary key value that is 1 larger than the previous row.

Example

Assume we want to create a table that consists of a primary key, last name, and first name. We use the following SQL:

CREATE TABLE USER_TABLE
(Userid int PRIMARY KEY IDENTITY(2,1),
 Last_Name nvarchar(50),
 First_Name nvarchar(50));

Upon creation, the table is empty.

We insert the first value:

INSERT INTO USER_TABLE VALUES ('Washington', 'George');

Now the table has the following values:

Table USER_TABLE

 Userid  Last_Name  First_Name 
 2  Washington  George 

Userid is 2 because we had specified the initial value to be 2.

Next we insert the second value:

INSERT INTO USER_TABLE VALUES ('Jefferson', 'Thomas');

Now the table has the following values:

Table USER_TABLE

 Userid  Last_Name  First_Name 
2 Washington  George 
3 Jefferson  Thomas 

userid for the second row is 3 because it is 1 larger than the previous Userid, which is 2.

Frequently Asked Questions

Q: What is the SQL IDENTITY property?
A: IDENTITY is a SQL Server column property that automatically generates a sequential numeric value for each new row inserted, commonly used for primary key columns.

Q: What is the difference between IDENTITY and AUTO_INCREMENT?
A: IDENTITY is the SQL Server syntax for auto-generated keys. AUTO_INCREMENT is the MySQL equivalent. Both produce sequential numbers automatically but use different keywords.

Q: Can you manually insert a value into an IDENTITY column?
A: Yes, but you must first run SET IDENTITY_INSERT table_name ON to allow manual inserts into an IDENTITY column. Remember to turn it OFF afterward.

Q: What do the seed and increment parameters mean in IDENTITY?
A: IDENTITY(seed, increment) — seed is the starting value for the first row, and increment is the step value added for each subsequent row. IDENTITY(1,1) starts at 1 and increases by 1 each row.



Next: SQL SEQUENCE And NEXTVAL

This page was last updated on March 19, 2026.




Copyright © 2026   1keydata.com   All Rights Reserved     Privacy Policy     About   Contact