Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDENTITY NOT NULL at Table Creation

Tags:

sql

null

identity

Can anyone please tell me whether the instruction IDENTITY NOT NULL at a table creation is redundant or not? I mean, judging by the message

DEFAULT or NULL are not allowed as explicit identity values.

I would say that any column declared as IDENTITY is implicitly also declared as NOT NULL, but I would like to make sure. Can anyone please confirm?

Thank you very much.

like image 216
Miguel Avatar asked Jun 01 '11 11:06

Miguel


People also ask

What is NOT NULL in Create Table?

The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.

Can we add identity column after creating the table?

Only one identity column can be created per table.

Can an identity column be NULL?

Additionally an identity column's definitions must not allow null values. One possible drawback of using an identity column is that only one identity column per table can be used.

Can we add NOT NULL constraint existing table?

It is possible to add a NOT NULL constraint to an existing table by using the ALTER TABLE statement. In this case, the column_name must not contain any NULL value before applying the NOT NULL constraint.


1 Answers

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

like image 85
Pranay Rana Avatar answered Sep 22 '22 18:09

Pranay Rana