Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Python Programs
    • Java Programs
    • SQL FAQ’s

Referential Integrity in SQL Server

by suresh

In this section, we will cover the list of Referential Integrity in SQL Server and their advantages.

The following are the available list of Referential Integrity constraint options in SQL Server

  • No Action: This is the default behavior. If you created a Foreign key without mentioning the Referential Integrity, then SQL will automatically assign No Action to it. If you set the Referential Integrity as No Action, and if you perform an update or delete in the parent table, then it will throw an error message.
  • Cascade: If you set the SQL Referential Integrity as Cascade. And if you perform an update or delete in the parent table, then those changes will automatically be applied to the dependent table rows.
  • Set Default: If you set the SQL Server Referential Integrity as Default. And perform an update or delete in the parent table, the foreign key column values will be replaced by the default value.
  • Set Null: If you set the SQL Referential Integrity as Set Null, and perform an update or delete in the parent table, the dependent records will become Nulls.

Before we get into the example, let me show you the table definition behind the tblDepartment table

USE [SQLTEST]
GO

CREATE TABLE [dbo].[tblDepartment](
	[ID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
	[DepartmentName] [varchar](50) NULL,
)

And the table definition behind the tblEmployee table is as shown below. I suggest you refer to Create Table article

USE [SQLTEST]
GO

CREATE TABLE [dbo].[tblEmployee](
	[EmpID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
	[FirstName] [nvarchar](255) NULL,
	[LastName] [nvarchar](255) NULL,
	[Education] [nvarchar](255) NULL,
	[YearlyIncome] [float] NULL,
	[Sales] [float] NULL,
	[DeptID] [int] NULL CONSTRAINT [DF_tblEmployee_DeptID] DEFAULT (2),
	CONSTRAINT [FK_tblDepartment_tblEmployee_DeptID] FOREIGN KEY([DeptID])
		REFERENCES [dbo].[tblDepartment] ([ID])
) 
GO

Let me show you the data inside tblDepartment table

Referential Integrity in SQL Server 1

And the data inside the tblEmployee table is:

Referential Integrity in SQL Server 2

To demonstrate Sql Server referential integrity, we will recreate the same Foreign key again and again. To achieve the same, we use the DROP Constraint statement along with the ALTER TABLE Statement to delete the existing Foreign key constraint

USE [SQLTEST]
GO
ALTER TABLE [dbo].[tblEmployee]  
DROP CONSTRAINT [FK_tblDepartment_tblEmployee_DeptID]

NO ACTION Referential Integrity in SQL Server Example

As we deleted the existing constraint from tblEMployee. Let me add the Foreign key constraint along with NO ACTION referential integrity in Sql Server.

Remember, this is the default option, even if you haven’t mentioned the integrity. By default, SQL Server will assign no action option.

As you can see from the below screenshot, we are using the Alter Table Statement to alter the table content. Then we used the ADD Constraint statement to add the Foreign key constraint.

-- No Action Referential Integrity in SQL Server
USE [SQLTEST]
GO
ALTER TABLE [dbo].[tblEmployee]  
ADD CONSTRAINT [FK_tblDepartment_tblEmployee_DeptID] FOREIGN KEY([DeptID])
        REFERENCES [dbo].[tblDepartment] ([ID])
        ON UPDATE NO ACTION ON DELETE NO ACTION

OUTPUT

Referential Integrity in SQL Server 3

Let me show you the same in the designer window.

Referential Integrity in SQL Server 4

Now let me perform Delete operation on tblDepartment. It means deleting the main table data (primary key value). From the below code snippet you can see, we are deleting a record from tblDepartment whose ID = 1.

-- No Action Referential Integrity in SQL Server
USE [SQLTEST]
GO
DELETE FROM [tblDepartment]
WHERE ID = 1

As you can see from the below screenshot, it is throwing an error. It is because No ACTION referential integrity will not allow you to perform Delete or Update option if there is any Foreign key dependency.

Referential Integrity in SQL Server 5

SET DEFAULT Referential Integrity in SQL Server Example

In this example, we will add a Foreign key constraint with Set Default referential Integrity in Sql Server.

Let me set the SQL Server referential integrity to default. It means whenever we perform Delete or Update on the Master Table, then the default value loaded in the Dept Id column (tblEmployee). I suggest you refer to the Default Constraint article.

-- Set Default Referential Integrity in SQL Server
USE [SQLTEST]
GO
ALTER TABLE [dbo].[tblEmployee]  
ADD CONSTRAINT [FK_tblDepartment_tblEmployee_DeptID] FOREIGN KEY([DeptID])
        REFERENCES [dbo].[tblDepartment] ([ID])
        ON UPDATE SET DEFAULT ON DELETE SET DEFAULT

OUTPUT

Referential Integrity in SQL Server 6

Let me show you the same in designer window.

Referential Integrity in SQL Server 7

Now let me perform Delete operation on tblDepartment. Let’s delete a record from tblDepartment whose ID = 6.

-- Set Default Referential Integrity in SQL Server
USE [SQLTEST]
GO
DELETE FROM [tblDepartment]
WHERE ID = 6

OUTPUT

Referential Integrity in SQL Server 8

Let us see the data in tblEmployee and tblDepartment. As you can see from the below screenshot, ID number 6 deleted from tblDepartment, and all the dependent records in tblEmployee replaced with the default value (i.e., 2)

Referential Integrity in SQL Server 9

SET NULL Referential Integrity in SQL Server Example

In this example, we will add a Foreign key constraint with Set Null referential Integrity in Sql Server.

It means, whenever we perform Delete, or Update on Master table (tblDepartment) then a NULL value will be loaded / Updated in the Dept Id column (tblEmployee).

-- Set Null Referential Integrity in SQL Server
USE [SQLTEST]
GO
ALTER TABLE [dbo].[tblEmployee]  
ADD CONSTRAINT [FK_tblDepartment_tblEmployee_DeptID] FOREIGN KEY([DeptID])
        REFERENCES [dbo].[tblDepartment] ([ID])
        ON UPDATE SET NULL ON DELETE SET NULL

OUTPUT

Referential Integrity in SQL Server 10

Let me show you the same in the designer window.

Referential Integrity in SQL Server 11

Now let me perform Delete operation on tblDepartment. It means deleting the primary key value. From the below code snippet, you can see, we are deleting record from tblDepartment whose ID = 1.

-- Set Null Referential Integrity in SQL Server
USE [SQLTEST]
GO
DELETE FROM [tblDepartment]
WHERE ID = 1

OUTPUT

Referential Integrity in SQL Server 12

Let us see the data in tblEmployee and tblDepartment. As you can see from the following screenshot, ID number 6 removed from tblDepartment, and all the dependent records in tblEmployee replaced with NULLS (i.e., Emp ID 1 and 13)

Referential Integrity in SQL Server 13

Cascade Referential Integrity in SQL Server Example

In this example, we will add a Foreign key constraint with Cascade referential Integrity in SQL Server. It means, whenever we perform Delete on Master table (tblDepartment), corresponding or dependent records from tblEmployee will delete.

-- Cascade Referential Integrity in SQL Server
USE [SQLTEST]
GO
ALTER TABLE [dbo].[tblEmployee]  
ADD CONSTRAINT [FK_tblDepartment_tblEmployee_DeptID] FOREIGN KEY([DeptID])
        REFERENCES [dbo].[tblDepartment] ([ID])
        ON UPDATE CASCADE ON DELETE CASCADE

OUTPUT

Referential Integrity in SQL Server 14

Let me show you the same in the designer window.

Referential Integrity in SQL Server 15

Now let me perform Delete operation on tblDepartment. From the below code snippet you can see, we are deleting a record from tblDepartment whose ID = 2.

-- Cascade Referential Integrity in SQL Server
USE [SQLTEST]
GO
DELETE FROM [tblDepartment]
WHERE ID = 2

OUTPUT

Referential Integrity in SQL Server 16

Let us see the data in tblEmployee, and tblDepartment. As you can see from the below screenshot, ID number 6 removed from tblDepartment, and all the dependent records in tblEmployee also removed

Referential Integrity in SQL Server 17

Use SSMS to set referential Integrity in SQL

If you are comfortable to use SQL Server Management Studio, then following the below steps to set referential integrity.

Within the object explorer, Expand the Database folder in which the table exists. Please select the table on which your Foreign key holds, then go to the Keys folder. Next, Right-click on the key name will open the context menu. Please select the Modify option

Referential Integrity in SQL Server 18

Once you click the Modify option, the SQL management studio will open the corresponding table in design mode, along with the Foreign Key Relationships window. Here set the Delete Rule and Update Rule property for SQL Server referential integrity as per your requirement.

Referential Integrity in SQL Server 19

Placed Under: SQL

  • Install SQL Server
  • Install SQL Management Studio
  • Uninstall Management Studio
  • Install AdventureWorks Database
  • SQL Management Studio Intro
  • Connect SQL with sqlcmd utility
  • SQL Attach Database
  • SQL Detach Database
  • SQL Restore Database
  • Restore Database using BAK
  • SQL Rename Database with Files
  • Get SQL Database Names
  • SQL Create Table
  • SQL Rename Table
  • SQL Alter Table
  • SQL Add Column
  • SQL Rename Column
  • Get SQL Table Names in a DB
  • Find SQL Table Dependencies
  • Rename SQL Table & Column
  • SQL Global & Local Temp Table
  • SQL Table Variable
  • SQL Derived Table
  • SQL DATALENGTH
  • SQL Data Types
  • DML, DDL, DCL & TCL Cmds
  • SQL Query Builder
  • SQL ALIAS
  • SQL SELECT Statement
  • SQL SELECT DISTINCT
  • SQL SELECT INTO Statement
  • SQL INSERT Statement
  • SQL INSERT INTO SELECT
  • SQL BULK INSERT or BCP
  • SQL UPDATE Statement
  • SQL UPDATE from SELECT
  • SQL DELETE Statement
  • SQL TRUNCATE Table
  • SQL CASE Statement
  • SQL MERGE Statement
  • SQL Subquery
  • SQL CTE
  • SQL PIVOT
  • SQL UNPIVOT
  • SQL Clauses Examples
  • SQL TOP Clause
  • SQL WHERE Clause
  • SQL ORDER BY Clause
  • SQL GROUP BY Clause
  • SQL HAVING Clause
  • SQL Primary Key
  • SQL Foreign Key
  • SQL Referential Integrity
  • SQL Check Constraint
  • SQL Unique Constraint
  • SQL Default Constraint
  • SQL Clustered Index
  • SQL Non Clustered Index
  • SQL Filtered Indexes
  • SQL COALESCE Function
  • SQL IS NOT NULL
  • SQL IS NULL Function
  • SQL ISNULL
  • SQL JOINS
  • SQL CROSS JOIN
  • SQL FULL JOIN
  • SQL SELF JOIN
  • SQL Outer Joins
  • SQL Cross Join Vs Inner Join
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL AND & OR Operators
  • SQL Arithmetic Operators
  • SQL BETWEEN Operator
  • SQL Comparison Operators
  • SQL LIKE
  • SQL EXCEPT
  • SQL EXISTS Operator
  • SQL NOT EXISTS Operator
  • SQL INTERSECT
  • SQL IN Operator
  • SQL NOT IN Operator
  • SQL UNION
  • SQL UNION ALL
  • SQL IF ELSE
  • SQL ELSE IF
  • SQL WHILE LOOP
  • SQL Nested While Loop
  • SQL BREAK Statement
  • SQL CONTINUE Statement
  • SQL GOTO Statement
  • SQL IIF Function
  • SQL CHOOSE Function
  • SQL Change Data Capture
  • SQL Table Partitioning
  • SQL Table Partition using SSMS
  • SQL TRY CATCH
  • SQL VIEWS
  • SQL User Defined Functions
  • SQL Alter User Defined Functions
  • SQL Stored Procedure Intro
  • Useful System Stored Procedures
  • SQL SELECT Stored Procedure
  • SQL INSERT Stored Procedure
  • SQL UPDATE Stored Procedure
  • Stored Procedure Return Values
  • Stored Procedure Output Params
  • Stored Procedure Input Params
  • Insert SP result into Temp Table
  • SQL Triggers Introduction
  • SQL AFTER INSERT Triggers
  • SQL AFTER UPDATE Triggers
  • SQL AFTER DELETE Triggers
  • SQL INSTEAD OF INSERT
  • SQL INSTEAD OF UPDATE
  • SQL INSTEAD OF DELETE
  • SQL STATIC CURSOR
  • SQL DYNAMIC CURSOR
  • SQL FORWARD_ONLY Cursor
  • SQL FAST_FORWARD CURSOR
  • SQL KEYSET CURSOR
  • SQL TRANSACTIONS
  • SQL Nested Transactions
  • SQL ACID Properties
  • Create SQL Windows Login
  • Create SQL Server Login
  • SQL Server Login Error
  • Create SQL Server Roles
  • SQL Maintenance Plan
  • Backup SQL Database
  • SQL Ranking Functions Intro
  • SQL RANK Function
  • SQL PERCENT_RANK Function
  • SQL DENSE_RANK Function
  • SQL NTILE Function
  • SQL ROW_NUMBER
  • SQL Aggregate Functions
  • SQL Date Functions
  • SQL Mathematical Functions
  • SQL String Functions
  • SQL CAST Function
  • SQL TRY CAST
  • SQL CONVERT
  • SQL TRY CONVERT
  • SQL PARSE Function
  • SQL TRY_PARSE Function
  • SQL Calculate Running Total
  • SQL Find Nth Highest Salary
  • SQL Reverse String
  • SQL FOR XML PATH
  • SQL FOR XML AUTO
  • SQL FOR XML RAW
  • C Tutorial
  • C# Tutorial
  • Java Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQL Tutorial
  • SQL Server Tutorial
  • R Tutorial
  • Power BI Tutorial
  • Tableau Tutorial
  • SSIS Tutorial
  • SSRS Tutorial
  • Informatica Tutorial
  • Talend Tutorial
  • C Programs
  • C++ Programs
  • Java Programs
  • Python Programs
  • MDX Tutorial
  • SSAS Tutorial
  • QlikView Tutorial

Copyright © 2021 | Tutorial Gateway· All Rights Reserved by Suresh

Home | About Us | Contact Us | Privacy Policy