This SQLite post explains how to use Foreign Keys with cascade delete in SQLite with syntax and examples.
A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQLite.
A foreign key with a cascade delete can only be defined in a CREATE TABLE statement.
The syntax for creating a foreign key with cascade delete using a CREATE TABLE statement in SQLite is:
Let's look at an example of how to create a foreign key with cascade delete using the CREATE TABLE statement in SQLite.
For example:
In this example, we've created a primary key on the departments table that consists of only one field - the department_id field. Then we've created a foreign key called fk_departments on the employees table that references the departments table based on the department_id field.
Because of the cascade delete, when a record in the departments table is deleted, all records in the employees table will also be deleted that have the same department_id value.
You can not use the ALTER TABLE statement to add a foreign key with cascade delete in SQLite. Instead you will need to rename the table, create a new table with the foreign key, and then copy the data into the new table.
The syntax to add a foreign key with cascade delete to an existing table in SQLite is:
First, let's start by creating our 2 tables (departments and employees):
Next, let's add some data to these tables:
Now, let's add a foreign key with cascade delete to the employees table:
In this example, we've created a foreign key (with cascade delete) called fk_departments that references the departments table based on the department_id field.
Now, let's demonstrate how the cascade delete works. Currently, we have the following records in the employees table:
employee_id | last_name | first_name | department_id |
---|---|---|---|
10000 | Smith | John | 30 |
10001 | Mark | Dave | 999 |
Now let's delete one of the records from the departments table and see what happens:
Even though we are deleting the record from the departments table where the department_id is 30, the foreign key (with cascade delete) will remove all records from the employees where the department_id is 30 as well.
After the cascade delete, the employees table will look like this:
employee_id | last_name | first_name | department_id |
---|---|---|---|
10001 | Mark | Dave | 999 |