Sunday, March 06, 2011

Can an identity column be nullable?

One of my friends asked me whether an identity column can be NULL.When he was viewing the table script he noticed that SQL Server adds NOT NULL constraint to identity columns automatically eventhough he did not speficy it when creating a table

Consider the following table script

create table test(id int identity(1,1), name varchar(1000))

Now Generate the script of the table from Management Studio. It generates the script as

CREATE TABLE [dbo].[test](
[id] [int] IDENTITY(1,1) NOT NULL
, [name] [varchar](1000) NULL
) ON [PRIMARY]

Eventhough NOT NULL constraint is not specified in the table script by default it is added. The identity column will never be NULL. So NOT NULL constraint is added default