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.
By the end of this lesson, you will understand:
DELETE CASCADE works in a relational database.DELETE CASCADE condition.DELETE CASCADE for database maintenance.
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.
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:
<table_1>: The parent table, containing a primary key column.<table_2>: The child table, containing a foreign key that references the parent table’s primary key.ON DELETE CASCADE: Ensures that when a record in the parent table is deleted, all matching records in the child table are also deleted.Let’s consider an example with employees and their performance reviews:
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:
reviews table’s employee_id column is a foreign key referencing the id column in the employees table.ON DELETE CASCADE, any review associated with a deleted employee will also be removed automatically.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
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;
employees table:id name department
1 Cooper Accounting
2 Indie HR
reviews table:id employee_id review
2 1 2021
3 2 2021
Using DELETE CASCADE simplifies database maintenance by:
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
);
In this lesson, you learned:
DELETE CASCADE in relational databases.DELETE CASCADE for efficient database management.
DELETE CASCADE is widely used in:
By using DELETE CASCADE, you can streamline database operations and ensure data consistency across related tables.