Scenario:
You are working as SQL Server developer, you need to create two tables with Primary -Foreign Key Relationship. You want to create Foreign Key Constraint with setting if record will be deleted from Referenced Table (Primary Key Column Table), it should not be deleted from Parent Table ( Foreign Key Constraint Table) instead the value should be updated to Null.
Solution:
We can use ON DELETE SET NULL with Foreign Key Constraint definition to implement above requirement.
Let's perform by using below script.
USE YourDatabaseName
GO
CREATETABLE dbo.Customer (
Customerid INTPRIMARYKEY
,FName VARCHAR(100)
,LName VARCHAR(100)
,SSN VARCHAR(10)
)
CREATETABLE dbo.Orders (
OrderId INTIdentity(1, 1)
,OrderitemName VARCHAR(50)
,OrderItemAmt INT
,Customer_id INTFOREIGNKEYREFERENCES
Customer(CustomerId) ONDELETESETNULL
)
--insert sample data
insertinto dbo.Customer
(CustomerId,FName, LName,SSN)
values
(1,'Aamir','Shahzad','000-000-00')
insertinto dbo.Orders
(OrderItemName,OrderItemAmt,Customer_Id)
values ('TV',1,1)
Check the data in tables by using Select query
Image may be NSFW. Clik here to view. ![]() |
How to create Foreign Key Constraint with ON DELETE SET NULL in SQL Server |
Let's delete the row from Referenced Table( Primary Key Column Table) and check if records still exists in Parent Table ( Foreign Key Constraint Table) and column value is updated to Null.
--Delete the Record from Referenced Table(PK Column Table)
Deletefrom dbo.Customer
where CustomerId=1
Image may be NSFW. Clik here to view. ![]() |
How to use ON DELETE SET NULL option with Foreign Key Constraint in SQL Server |
As we can see that the record is deleted from Referenced Table( Primary Key Column Table) but still present in Parent Table ( Foreign Key Constraint Table) but value is updated to Null as expected.