Delete Dependent Data with DELETE CASCADE

Managing dependent data across multiple tables can be challenging, especially as databases grow in size and complexity. The DELETE CASCADE statement provides a powerful solution by automatically removing associated records in child tables when a parent record is deleted.

What You’ll Learn

By the end of this lesson, you will understand:

Understanding DELETE CASCADE

The DELETE CASCADE statement allows you to delete rows in a parent table and automatically remove any associated rows in child tables. This is done by defining a foreign key constraint with the ON DELETE CASCADE condition.

Syntax

CREATE TABLE  (
   id INT NOT NULL PRIMARY KEY
);

CREATE TABLE  (
   id INT NOT NULL PRIMARY KEY,
    INT FOREIGN KEY REFERENCES (id) ON DELETE CASCADE
);
    

In this example:

DELETE CASCADE Example

Let’s consider an example with employees and their performance reviews:

Schema

employees table:

CREATE TABLE employees (
   id INT NOT NULL PRIMARY KEY,
   name TEXT NOT NULL,
   department TEXT NOT NULL
);
    

reviews table:

CREATE TABLE reviews (
   id INT NOT NULL PRIMARY KEY,
   employee_id INT FOREIGN KEY REFERENCES employees(id) ON DELETE CASCADE,
   review TEXT NOT NULL
);
    

In this schema:

Sample Data

employees table:

id   name    department
1    Cooper  Accounting
2    Indie   HR
3    Kota    Project Manager
    

reviews table:

id   employee_id   review
1    3              2020
2    1              2021
3    2              2021
4    3              2021
    

DELETE CASCADE in Action

When you delete a record from the employees table, the corresponding records in the reviews table are automatically removed:

DELETE FROM employees WHERE name = 'Kota';
    

This action triggers:

DELETE FROM reviews WHERE employee_id = 3;
    

Updated Tables

employees table:
id   name    department
1    Cooper  Accounting
2    Indie   HR
    
reviews table:
id   employee_id   review
2    1              2021
3    2              2021
    

Benefits of DELETE CASCADE

Using DELETE CASCADE simplifies database maintenance by:

SQL Commands Recap

To use DELETE CASCADE, ensure that foreign keys are enabled in SQLite3:

PRAGMA foreign_keys = ON;
    

Then, define your schema with ON DELETE CASCADE:

CREATE TABLE parent_table (
   id INT NOT NULL PRIMARY KEY
);

CREATE TABLE child_table (
   id INT NOT NULL PRIMARY KEY,
   parent_id INT FOREIGN KEY REFERENCES parent_table(id) ON DELETE CASCADE
);
    

What You Learned

In this lesson, you learned:

Real-World Applications

DELETE CASCADE is widely used in:

By using DELETE CASCADE, you can streamline database operations and ensure data consistency across related tables.