Create foreign key that allows null values in SQL Server

Joseph Kashishian 20 Reputation points
2023-10-10T15:04:59.6966667+00:00

in the client table we have a sex_id field.

I want to create a foreign key that allows null values in the client table and that has a contraint that references the sex table (sex_Id)

Is this possible in sql server and what does the script look like

this is what I have but you can't enter null values in the client table. I want to make this possible.

ALTER TABLE [dbo].[Client] WITH CHECK ADD CONSTRAINT [FK_sex_id] FOREIGN KEY([sex_ID])

REFERENCES [lu].[sex] ([sex_ID])

ON UPDATE CASCADE

ON DELETE CASCADE

GO

ALTER TABLE [dbo].[Client] CHECK CONSTRAINT [FK_sex_id]

GO

SQL Server Other
{count} votes

3 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-10-10T15:16:26.5433333+00:00

    You can not use null in a foreign key because null means no match (empty set). Just define an unspecified value.

    0 comments No comments

  2. Dan Guzman 9,401 Reputation points
    2023-10-10T16:11:07.25+00:00

    A nullable column may be used as a foreign key. NULL values will not be checked for the referential integrity check. Example DDL below

    CREATE TABLE dbo.sex(
    	  sex_ID int NOT NULL
    		CONSTRAINT PK_Sex PRIMARY KEY
    	, Description varchar(10) NOT NULL
    );
    
    CREATE TABLE dbo.Client(
    	  ClientID int NOT NULL IDENTITY
    	, sex_ID int NULL
    );
    
    ALTER TABLE [dbo].[Client] WITH CHECK ADD CONSTRAINT [FK_Client_sex] FOREIGN KEY([sex_ID])
    	REFERENCES [sex] ([sex_ID])
    	ON UPDATE CASCADE
    	ON DELETE CASCADE;
    GO
    
    ALTER TABLE [dbo].[Client] CHECK CONSTRAINT [FK_Client_sex];
    GO
    
    0 comments No comments

  3. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-10-10T20:59:50.45+00:00

    As Dan says, this is perfectly possible in SQL Server and it is straightforward to do. I suspect that the real problem is that when you think you are inserting NULL in the Client field, you are inserting an empty string, a zero or something similar.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.