What is a Referential Integrity Constraint?
Referential integrity constraints, told as a story about the student council's rule that only a name on the roster can go on the president list.
A name on the president list isn't on the roster at all.A name that isn't in the original (the roster) got written into the list that refers to it (the president list).
If a president isn't on the roster, nobody can later confirm who that person is.A president who isn't on the roster has no record to check against.
Referential integrity is the rule that only a name the original roster actually has may go on the list that refers to it.Trying to write a name the roster doesn't have gets blocked outright.
When a student disappears from the original, one of three common options decides what happens to the list that refers to them.One of CASCADE, RESTRICT, or SET NULL is chosen ahead of time, to fit the situation.
Too strict a constraint makes everyday work inconvenient.A strict rule like RESTRICT makes everyday tasks, like processing a transfer, a hassle.
Referential integrity = the rule that anything referencing another table must point to a value that actually exists there (or be left empty). When the original is removed, you decide in advance whether to delete it along, block the delete, or leave it blank.
A referential integrity constraint requires that a foreign key (FK) value in a relational database either match a primary key (PK) that actually exists in the referenced table or be NULL. When the original row is deleted or updated, an option such as CASCADE (delete/update together), RESTRICT (block the change), or SET NULL (clear the reference) is chosen to preserve data consistency (SET DEFAULT and NO ACTION also exist).
When grown-ups say it
- Referential Integrity Constraint
- The rule that a reference must point to a value that exists in the original. A basic consistency rule in relational databases.
- Foreign Key (FK)
- The field that points to another roster. It usually points to the original roster's primary key.
- Primary Key (PK)
- The ID that points to exactly one person on the roster. This is what a foreign key points to.
- CASCADE
- Deleting the reference whenever the original is removed. Cleans up automatically, but can delete more than intended.
- RESTRICT
- Blocking deletion of the original while something still refers to it. Keeps data safe, but sometimes makes work inconvenient.
- SET NULL
- Just leaving the referring field blank. Removes the original but keeps the referring record.
- Normalization
- The rule for splitting a roster so each fact is written once. Referential integrity keeps rosters split by normalization correctly linked. → the rule of writing it once
- Transaction
- The unit of work that changes a roster. A change that breaks the constraint is rejected and rolled back.