This SQLite post explains how to use Foreign Keys with "set null on delete" in SQLite with syntax and examples.
A foreign key with "set null on delete" means that if a record in the parent table is deleted, then the corresponding records in the child table will have the foreign key fields set to null. The records in the child table will not be deleted.
A foreign key with a "set null on delete" can only be defined in a CREATE TABLE statement.
The syntax for creating a foreign key with "set null on delete" using a CREATE TABLE statement in SQLite is:
Let's look at an example of how to create a foreign key with "set null on 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 ON DELETE SET NULL, when a record in the departments table is deleted, all corresponding records in the employees table will have the department_id set to NULL.
You can not use the ALTER TABLE statement to add a foreign key with "set null on 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 "set null on 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 ON DELETE SET NULL to the employees table:
In this example, we've created a foreign key (with set null on delete) called fk_departments that references the departments table based on the department_id field.
Now, let's demonstrate how the ON DELETE SET NULL 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 set null on delete) will update the employees table and change all the department_id values to NULL where the department_id is 30.
After the delete, the employees table will look like this:
employee_id | last_name | first_name | department_id |
---|---|---|---|
10000 | Smith | John | NULL |
10001 | Mark | Dave | 999 |