Course contentsShow
← Databases & SQL
Lesson 65 of 1,9531. Relational FoundationsFree lesson

Reference Integrity Enforcement

Configure cascade actions to automatically handle child records when parent records change.

Automating Cleanup with Cascade Actions

In this lesson, you will learn how to configure your database to automatically handle child records when a parent record is deleted or updated.

The Problem of "Orphaned" Data

When you enforce Reference Integrity using a FOREIGN KEY constraint, the database prevents you from deleting a parent record (like a Customer) if there are still child records (like Orders) pointing to it. This protects your data quality, but it can be annoying. If you decide to delete a customer, you shouldn't have to manually hunt down and delete every single one of their orders first.

Enter Cascade Actions

Cascade actions are instructions you give to the database to handle this "cleanup" automatically. Instead of throwing an error when you delete a parent, the database performs a secondary action on all related child records.

There are two primary actions we care about:

  1. ON DELETE CASCADE: If you delete a parent row, the database automatically deletes all related child rows.
  2. ON UPDATE CASCADE: If the primary key of a parent changes, the database automatically updates the foreign key in all child rows to match.

Putting it into Practice

When you define your table, you attach these instructions to your FOREIGN KEY constraint. Here is how it looks in a table definition:

CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    CustomerID INT,
    OrderDate DATE,
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
    ON DELETE CASCADE
    ON UPDATE CASCADE
);

In this example, if you delete a customer from the Customers table, the database silently removes all associated orders from the Orders table. Similarly, if a customer's ID changes, your orders will automatically track that new ID, keeping your relationships intact without you writing extra queries.

This mechanism ensures that your data remains perfectly synchronized. You no longer have to worry about "orphaned" records cluttering your database or causing constraint violations, because the database enforces the integrity rules behind the scenes.

Key Takeaway: Cascade actions automate the maintenance of relationships, ensuring that changes to parent records are automatically mirrored in your child data to prevent broken links.