Bird
Raised Fist0
SQLquery~5 mins

Referential integrity enforcement in SQL

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Referential integrity ensures that relationships between tables stay correct and consistent. It prevents errors like linking to data that does not exist.
When you have two tables where one depends on the other, like orders linked to customers.
When you want to avoid deleting data that other data still needs.
When you want to make sure every reference in one table matches a valid entry in another.
When you want the database to automatically update or delete related data safely.
When you want to keep your data clean and reliable without manual checks.
Syntax
SQL
CREATE TABLE ChildTable (
  id INT PRIMARY KEY,
  parent_id INT,
  FOREIGN KEY (parent_id) REFERENCES ParentTable(id)
    ON DELETE CASCADE
    ON UPDATE CASCADE
);
The FOREIGN KEY links a column in one table to a column in another table.
ON DELETE and ON UPDATE define what happens if the parent data changes or is removed.
Examples
This example prevents deleting a customer if they have orders (RESTRICT) but updates order records if the customer ID changes.
SQL
CREATE TABLE Orders (
  order_id INT PRIMARY KEY,
  customer_id INT,
  FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
    ON DELETE RESTRICT
    ON UPDATE CASCADE
);
If a post is deleted, the post_id in Comments is set to NULL, keeping comments but removing the link.
SQL
CREATE TABLE Comments (
  comment_id INT PRIMARY KEY,
  post_id INT,
  FOREIGN KEY (post_id) REFERENCES Posts(post_id)
    ON DELETE SET NULL
);
If a course is deleted, all enrollments for that course are also deleted automatically.
SQL
CREATE TABLE Enrollment (
  student_id INT,
  course_id INT,
  PRIMARY KEY (student_id, course_id),
  FOREIGN KEY (student_id) REFERENCES Students(student_id),
  FOREIGN KEY (course_id) REFERENCES Courses(course_id)
    ON DELETE CASCADE
);
Sample Program
We create two tables: Departments and Employees. Employees link to Departments by dept_id. When a department is deleted, employees in that department have their dept_id set to NULL. After deleting department 1, employees Alice and Charlie lose their department link.
SQL
CREATE TABLE Departments (
  dept_id INT PRIMARY KEY,
  dept_name VARCHAR(50)
);

CREATE TABLE Employees (
  emp_id INT PRIMARY KEY,
  emp_name VARCHAR(50),
  dept_id INT,
  FOREIGN KEY (dept_id) REFERENCES Departments(dept_id)
    ON DELETE SET NULL
);

INSERT INTO Departments VALUES (1, 'Sales'), (2, 'HR');
INSERT INTO Employees VALUES (101, 'Alice', 1), (102, 'Bob', 2), (103, 'Charlie', 1);

DELETE FROM Departments WHERE dept_id = 1;

SELECT * FROM Employees ORDER BY emp_id;
OutputSuccess
Important Notes
Referential integrity helps avoid broken links between tables.
ON DELETE CASCADE deletes related rows automatically.
ON DELETE SET NULL keeps rows but removes the link by setting foreign key to NULL.
Summary
Referential integrity keeps data relationships correct and safe.
Foreign keys connect tables and enforce these rules.
You can control what happens when related data changes or is deleted.

Practice

(1/5)
1. What is the main purpose of referential integrity in a database?
easy
A. To speed up query execution
B. To ensure relationships between tables remain consistent
C. To store large amounts of data efficiently
D. To create backup copies of the database

Solution

  1. Step 1: Understand referential integrity concept

    Referential integrity ensures that foreign keys in one table correctly reference existing rows in another table.
  2. Step 2: Identify the main purpose

    This prevents orphan records and keeps data relationships consistent and safe.
  3. Final Answer:

    To ensure relationships between tables remain consistent -> Option B
  4. Quick Check:

    Referential integrity = consistent relationships [OK]
Hint: Referential integrity means keeping table links correct [OK]
Common Mistakes:
  • Confusing referential integrity with performance optimization
  • Thinking it creates backups
  • Assuming it stores data efficiently
2. Which SQL statement correctly defines a foreign key with referential integrity enforcement?
easy
A. INSERT INTO Orders (OrderID, CustomerID) VALUES (1, 100);
B. CREATE TABLE Orders (OrderID INT, CustomerID INT PRIMARY KEY);
C. ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);
D. SELECT * FROM Orders WHERE CustomerID = Customers.CustomerID;

Solution

  1. Step 1: Identify foreign key syntax

    The correct syntax to add a foreign key is using ALTER TABLE with ADD FOREIGN KEY referencing another table's column.
  2. Step 2: Check each option

    ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID); correctly adds a foreign key constraint. CREATE TABLE Orders (OrderID INT, CustomerID INT PRIMARY KEY); wrongly sets CustomerID as primary key without foreign key. INSERT INTO Orders (OrderID, CustomerID) VALUES (1, 100); is an insert, not a constraint. SELECT * FROM Orders WHERE CustomerID = Customers.CustomerID; is a select query, not a constraint definition.
  3. Final Answer:

    ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID); -> Option C
  4. Quick Check:

    Foreign key syntax = ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID); [OK]
Hint: Foreign keys use ALTER TABLE ADD FOREIGN KEY ... REFERENCES [OK]
Common Mistakes:
  • Confusing primary key with foreign key syntax
  • Using INSERT or SELECT instead of constraint definition
  • Missing REFERENCES keyword
3. Given these tables:
CREATE TABLE Customers (CustomerID INT PRIMARY KEY, Name VARCHAR(50));
CREATE TABLE Orders (OrderID INT PRIMARY KEY, CustomerID INT, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) ON DELETE CASCADE);

What happens if a customer with CustomerID = 5 is deleted?
medium
A. All orders with CustomerID = 5 are also deleted
B. The delete fails due to foreign key constraint
C. Orders with CustomerID = 5 remain unchanged
D. CustomerID in Orders is set to NULL for those orders

Solution

  1. Step 1: Understand ON DELETE CASCADE

    The ON DELETE CASCADE option means deleting a referenced row causes all related rows to be deleted automatically.
  2. Step 2: Apply to the scenario

    Deleting customer with CustomerID=5 will delete all orders linked to that customer in Orders table.
  3. Final Answer:

    All orders with CustomerID = 5 are also deleted -> Option A
  4. Quick Check:

    ON DELETE CASCADE = delete related rows [OK]
Hint: ON DELETE CASCADE deletes related rows automatically [OK]
Common Mistakes:
  • Thinking delete will fail due to constraint
  • Assuming related rows remain unchanged
  • Confusing CASCADE with SET NULL
4. You have this foreign key constraint:
FOREIGN KEY (ProductID) REFERENCES Products(ProductID) ON DELETE SET NULL

Which error will occur if you try to delete a product that is referenced by an order, but the ProductID column in Orders is defined as NOT NULL?
medium
A. Delete fails due to NOT NULL constraint violation
B. Delete succeeds and sets ProductID to NULL
C. Delete succeeds and removes the order row
D. Delete succeeds without affecting Orders

Solution

  1. Step 1: Understand ON DELETE SET NULL behavior

    This option sets the foreign key column to NULL in referencing rows when the referenced row is deleted.
  2. Step 2: Check NOT NULL constraint conflict

    If the foreign key column is NOT NULL, setting it to NULL violates the column constraint, causing the delete to fail.
  3. Final Answer:

    Delete fails due to NOT NULL constraint violation -> Option A
  4. Quick Check:

    SET NULL + NOT NULL column = delete fails [OK]
Hint: SET NULL fails if foreign key column is NOT NULL [OK]
Common Mistakes:
  • Assuming delete succeeds and sets NULL anyway
  • Thinking delete removes referencing rows
  • Ignoring NOT NULL constraint on foreign key
5. You want to enforce referential integrity between Employees and Departments tables. When a department is deleted, you want all employees in that department to be reassigned to department ID 0 (which means 'Unassigned'). Which foreign key option should you use?
hard
A. FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE RESTRICT
B. FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE CASCADE
C. FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE SET NULL
D. FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE SET DEFAULT

Solution

  1. Step 1: Understand ON DELETE SET DEFAULT

    This option sets the foreign key column to its default value when the referenced row is deleted.
  2. Step 2: Match requirement

    Since you want employees reassigned to department ID 0, set DepartmentID column default to 0 and use ON DELETE SET DEFAULT to assign that value automatically.
  3. Final Answer:

    FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE SET DEFAULT -> Option D
  4. Quick Check:

    Reassign on delete = ON DELETE SET DEFAULT [OK]
Hint: Use ON DELETE SET DEFAULT to assign default on delete [OK]
Common Mistakes:
  • Using CASCADE deletes employees instead of reassigning
  • Using SET NULL when column disallows NULL
  • Using RESTRICT blocks deletion