Google

Tuesday, October 9, 2007

The Meaning of IDENTITY(1,1) in SQL Server

Using the Northwind Database as an example, a new Table called SalesPersons can be created with the following lines of code:

SqlCommand CreateTableCommand = new SqlCommand();
CreateTableCommand.Connection = NorthwindConnection;
CreateTableCommand.CommandType = CommandType.Text;
CreateTableCommand.CommandText =
"CREATE TABLE SalesPersons " +
"([SalesPersonID][int]IDENTITY(1,1)NOT NULL," +
"[FirstName][nvarchar](50) NULL," +
"[LastName][nvarchar](50) NULL)";

CreateTableCommand.Connection.Open();
CreateTableCommand.ExecuteNonQuery();
CreateTableCommand.Connection.Close();



Notice the SQL Command:

CREATE TABLE SalesPersons
(
[SalesPersonID][int]IDENTITY(1,1)NOT NULL,
[FirstName][nvarchar](50) NULL,
[LastName][nvarchar](50) NULL
)

What is the meaning of IDENTITY(1,1) ?


Answer:
It is the Property of the SalesPersonID. See figure below:



It sets the Property of SalesPersonID to be auto-incrementing (Identity Increment = 1) and also uniquely identifies the rows of this Table (Identity Seed = 1). These are the pre-requisite properties of a potential Primary Key.