In SQL Server, an Auto Increment or Identity column is a column in a table that automatically generates a unique value for each new row inserted into the table. This is typically used for primary key columns, where each row needs a unique identifier.
Syntax for Identity Column
CREATE TABLE TableName (
ColumnName INT IDENTITY(1,1) PRIMARY KEY,
OtherColumn VARCHAR(100)
);
IDENTITY(1,1)Example of Using an Identity Column
CREATE TABLE Employees (
EmployeeID INT IDENTITY(1,1) PRIMARY KEY,
EmployeeName VARCHAR(100),
Department VARCHAR(50)
);
-- Inserting data
INSERT INTO Employees (EmployeeName, Department)
VALUES ('John Doe', 'HR'),
('Jane Smith', 'IT'),
('Emily Johnson', 'Finance');
-- Result:
-- EmployeeID values will be automatically generated starting from 1.
After inserting the data, the EmployeeID values would automatically be:
CREATE TABLE Products (
ProductID INT IDENTITY(1000,5) PRIMARY KEY, -- Starts at 1000 and increments by 5
ProductName VARCHAR(100)
);
This will create an identity column where the first value is 1000 and each subsequent value increases by 5 (1000, 1005, 1010, etc.).