Define Referential integrity in SQL Server
Loading
Define Referential integrity in SQL Server
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Muhammad Imran AnsariPosted Jan 27, 2025, 7:27 AM
Referential integrity in SQL Server is a set of rules that ensures relationships between tables remain accurate and consistent. It is enforced through foreign key constraints, which link a column (or columns) in one table to the primary key in another table, preventing invalid or orphaned data.
Foreign Key Constraint:
A foreign key in one table must reference a valid primary key in the related table.
Data Consistency:
Ensures that any foreign key value in the child table corresponds to a primary key value in the parent table.
Actions to Maintain Integrity:
SQL Server provides options to handle updates or deletions in the parent table:
ON DELETE CASCADE: Deletes related rows in the child table when a parent row is deleted.
ON UPDATE CASCADE: Updates foreign key values in the child table when the primary key in the parent table changes.
SET NULL: Sets the foreign key value to NULL when the parent record is deleted or updated.
SET DEFAULT: Sets the foreign key value to a predefined default value.
NO ACTION: Prevents changes to the parent row if related child rows exist.
Here is example script to understand this.
Without Referential Integrity
In this case, there’s no guarantee that CustomerID in the Orders table matches a valid CustomerID in the Customers table.
With Referential Integrity:
Sangeetha SPosted Jan 27, 2025, 6:11 AM
Referential integrity in SQL Server is a database concept that ensures relationships between tables remain consistent. It enforces rules that maintain the validity and accuracy of data across related tables, primarily through the use of foreign keys.
Key Points:Foreign Keys: A foreign key in a child table points to a primary key in a parent table. This establishes a relationship between the two tables.
Consistency: Referential integrity ensures that:
Actions: SQL Server allows specific actions when referential integrity is violated: