SQLMentor // glossary

Referential Integrity

Referential integrity is the guarantee that a foreign key value always matches an existing primary key value in the table it references — or is NULL. The database enforces it automatically once a foreign key constraint is defined.

In practice, this means you can't insert an order for a customer_id that doesn't exist, and (by default) you can't delete a customer who still has orders referencing them — the database rejects the operation to protect referential integrity, unless the foreign key is defined with a cascading rule.

This is the mechanism that makes normalization safe: splitting data across related tables only works reliably if the database actively prevents the links between them from pointing at nothing.

Example

ALTER TABLE employees
  ADD CONSTRAINT fk_dept
  FOREIGN KEY (department_id) REFERENCES departments(department_id);
-- Any employees.department_id must now exist in departments, or be NULL