Referential Integrity

Learning Objective

Understand how databases maintain consistency when records are linked. We will explore what happens to "child" records when a "parent" record is deleted, using a simple library analogy.

Interactive Sandbox: The Library System

Students Parent
1
M
Borrows
Books Child

Imagine a library. We have a list of Students (the Parent) and a list of Borrowed Books (the Child). The books reference the students. What should the database do with a student's books if that student leaves the school (is deleted)? Try deleting a student below to see the database constraint rules in action!

Students (Parent Table)

Primary Key: StudentID
StudentID Name Action

Borrowed Books (Child Table)

Foreign Key: BorrowerID
RecordID Book Title BorrowerID Status

Common Misconception

"A Foreign Key must always match an existing Primary Key, so it can never be empty."

Correction: While a Foreign Key usually points to a valid Primary Key, it can be empty (NULL) depending on the system's rules. If we use SET NULL during deletion, the database breaks the link, leaving the child record intact but without an owner (Orphan Records).

DSE Trap: The Two Integrities

Entity Integrity

Focuses on the Primary Key (PK). It ensures every record is unique and the PK is never allowed to be NULL.

Referential Integrity

Focuses on the Foreign Key (FK). Ensures relationships are valid. FK must match a PK, or can be NULL.

Key Takeaways: ON DELETE Behaviors

RESTRICT
ON DELETE RESTRICT

The safest approach. The database actively blocks the deletion of a parent record if child records still depend on it. Prevents accidental data fragmentation.

CASCADE
ON DELETE CASCADE

The chain reaction. Deleting the parent automatically deletes all linked child records. Powerful, but dangerous if used carelessly without understanding business rules.

SET NULL
ON DELETE SET NULL

The preservationist. The parent is deleted, but child records are kept. Their link (FK) is erased to prevent invalid references, creating 'Orphan Records'.

Think & Link: Real World Scenarios

E-commerce (Customers & Orders)

If a user deletes their account, we shouldn't CASCADE delete their past orders! The accounting department still needs those records. Instead, we SET NULL or mark the user as deactivated.

Social Media (Posts & Comments)

If a user deletes a post, all comments under it should probably disappear too. Here, a CASCADE constraint makes perfect sense!

Knowledge Check: Mini Quiz

1. When a database prevents you from deleting a record because other records depend on it, which integrity rule is at work?

2. To keep order history even after a customer deletes their account, which ON DELETE action should be used for the Foreign Key in the Orders table?