7

Is it required to make foreign key column in a table as NOT NULL, If we not written explicitly foreign key column as not null what it will be? Can it contain null values?

And what is the Difference between following two statements:

[PhoneId] [int] NOT NULL FOREIGN KEY REFERENCES [dbo].[tbl_PhoneNumber](PhoneNumberId) [PhoneId] [int] FOREIGN KEY REFERENCES [dbo].[tbl_PhoneNumber](PhoneNumberId) 
2
  • The difference is that the second definition will allow Nulls in the column. The relationships will be 1 :: 0..n in the first and 0..1 :: 0..n in the second (if you are familiar with this notation). Commented Oct 26, 2013 at 9:17
  • @ypercube - That depends on the ANSI null default database option and whether or not the client library calls SET ANSI_NULL_DFLT_ON Commented Oct 26, 2013 at 14:20

3 Answers 3

7

Is it required to make foreign key column in a table as NOT NULL,

No it is not required. MSDN says that:-

When a value other than NULL is entered into the column of a FOREIGN KEY constraint, the value must exist in the referenced column; otherwise, a foreign key violation error message is returned. To make sure that all values of a composite foreign key constraint are verified, specify NOT NULL on all the participating columns.

So the simple answer to your question is NO IT IS NOT REQUIRED.

A foreign key attribute can contain NULL values as well.

Your second definition will allow Nulls in the column.

From here:-

When a FOREIGN KEY constraint is added to an existing column or columns in the table SQL Server, by default checks the existing data in the columns to ensure that all values, except NULL, exist in the column(s) of the referenced PRIMARY KEY or UNIQUE constraint.

Also check Foreign Key Constraints

Sign up to request clarification or add additional context in comments.

Comments

1

According to sql normalization rule foreign key value must be equal to primary key value or NULL, so it will contain either NULL value of one value from primary key table row.

Comments

0

It is not required. A foreign key attribute without NOT NULL can contain NULL values, and this can be used to indicate that no such tuple in the referenced relation is applicable.

2 Comments

Means by default it can contain null values also!
@DhananjayPatil:- Yes it may contain NULL values!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.