What is the purpose of a Foreign Key constraint? Explain the difference between ON DELETE CASCADE and ON DELETE SET NULL in terms of data integrity.
Last updated
A foreign key constraint enforces referential integrity by guaranteeing that a value in the child table corresponds to a real row in the parent table. ON DELETE CASCADE and ON DELETE SET NULL differ in whether the child rows are removed or simply detached when the parent disappears.
Purpose of a foreign key:
Ties related tables together and rejects orphaned references (e.g. an order pointing to a deleted customer).
Documents the relationship and lets the DB, not application code, enforce it.
ON DELETE CASCADE:Child rows are deleted with the parent: good when children are meaningless without the parent (order line items).
Integrity view: no dangling rows, but risk of unintentionally deleting large chains of data.
ON DELETE SET NULL:Child rows survive but their FK becomes
NULL: good when the child is still valuable independently (an employee whose department is dropped).Integrity view: preserves history/records at the cost of losing the relationship link; requires a nullable column.
- https://neon.com/blog/the-silent-syntax-difference-in-foreign-keys-between-postgres-and-mysql
- https://medium.com/@sunnywilson.veshapogu/restrict-vs-cascade-vs-set-null-in-sql-choosing-the-right-foreign-key-rule-6d7c98484710
- https://www.postgresql.org/docs/current/ddl-constraints.html
- https://dev.to/tbson87/on-delete-set-null-vs-cascade-vs-restrict-in-postgresql-which-to-use-1n6l
- https://dev.mysql.com/doc/en/create-table-foreign-keys.html
- https://www.geeksforgeeks.org/dbms/difference-between-on-delete-cascade-and-on-delete-set-null-in-dbms/
- https://www.hackerone.com/blog/navigating-waters-foreign-key-constraints-role-update-and-delete