Explain the concept of referential integrity and how foreign keys enforce it.
Last updated
Referential integrity is the guarantee that a foreign key value always refers to an existing, valid row in the parent table (or is NULL). Foreign keys enforce it by rejecting or handling operations that would leave a child row pointing at a non-existent parent.
What it enforces:
No orphan rows: you can't insert or update a child with a key that has no matching parent.
You can't delete or change a parent's key while children still reference it, unless a cascade or
SET NULLrule applies.
How the FK enforces it:
The referenced parent column must be a primary or unique key.
The database checks the constraint at write time (and per-statement or deferred within a transaction).
Reaction rules:
RESTRICT/NO ACTIONblock the change;CASCADE,SET NULL,SET DEFAULTpropagate it.Note: a NULL foreign key is allowed and means 'no relationship', which does not violate integrity.
[lang:sql]
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT REFERENCES customers(id) ON DELETE RESTRICT
);
-- Fails: no customer 999 exists
INSERT INTO orders (id, customer_id) VALUES (1, 999);
- https://www.postgresql.org/docs/current/tutorial-fk.html
- https://www.postgresql.org/docs/current/ddl-constraints.html
- https://learn.microsoft.com/en-us/sql/relational-databases/tables/primary-and-foreign-key-constraints?view=sql-server-ver17
- https://www.freecodecamp.org/news/how-relational-database-constraints-work-and-why-theyre-important/
- https://motherduck.com/glossary/referential-integrity/
- https://thoughtbot.com/blog/referential-integrity-with-foreign-keys
- https://www.geeksforgeeks.org/postgresql/postgresql-foreign-key/