I am learning SQL and particularly progressing at Foreign Keys. I understand the difference between set NULL vs set CASCADE, but not yet clear on the use cases for them.
When do you set NULL and when do you set CASCADE for a foreign key?
I am learning SQL and particularly progressing at Foreign Keys. I understand the difference between set NULL vs set CASCADE, but not yet clear on the use cases for them.
When do you set NULL and when do you set CASCADE for a foreign key?
Generally we prefer ON DELETE SET NULL
when the lifecycle of the parent is to be shorter then the lifecycle of the child.
For example consider a delivery system where each Parcel
is assigned to exactly one Route
/Trip. So there exists FK Parcel.RouteId
to Route.Id
. A system user can create a Route
, assign some Parcel
s to it (set Parcel.RouteId
). A bit later the user decides to delete a Route
for a reason. Definetly we don't want Parcel
s in the Route
to be deleted too. So we specify ON DELETE SET NULL
for this FK.
There are three modes to consider.
In set NULL, the foreign key will notice the deleting of the parent row. Then the foreign key will orphan the child rows by updating the ParentId on each child row to null.
In set CASCADE, the foreign key will notice the deleting of the parent row. Then the foreign key will delete the child rows.
The main consideration between selecting these two modes, is whether parent-less child rows are permitted.
In an enforced foreign key (the default behavior), the foreign key will notice the deleting of the parent row and notice that there are child rows. Then the foreign key will rollback the transaction, restoring the parent row.
The main consideration between selecting this mode and the other two, is whether the database or the user should handle resolving deletes that violate the foreign key. By rolling back the transaction the database prevents accidental deletes/updates of the child rows. This allows the user to evaluate/change their request.