1.Understanding Referential Integrity
Referential integrity is the guarantee that a foreign key value always points to a row that genuinely exists. PostgreSQL enforces it automatically for any column declared REFERENCES another table — an INSERT or UPDATE that would point at a nonexistent row is rejected outright.
Key features
- A FOREIGN KEY constraint is what makes referential integrity enforced rather than merely assumed
- The referenced column must be UNIQUE or PRIMARY KEY on the other table — integrity requires the target to be unambiguous
- Referential integrity is checked on both sides: inserting/updating a child row, and deleting/updating a referenced parent row
- A table with no foreign key constraint can still store an integer column that "means" a reference — but nothing stops it from becoming stale
- Referential integrity failures show up as either a rejected write (if enforced) or a silently orphaned row (if not)
With and without an enforced foreign key
- customer_id INT (no constraint)
- nothing verifies the value refers to a real customer
- a deleted customer silently orphans every order that "referenced" them
- correctness depends entirely on application code remembering to check
- customer_id INT REFERENCES customers(id)
- every INSERT/UPDATE is checked against customers
- deleting a referenced customer is blocked (or cascaded/nulled, per ON DELETE)
- correctness is guaranteed by PostgreSQL itself
Command
CREATE TABLE customers (id SERIAL PRIMARY KEY);
CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT REFERENCES customers(id));Referential integrity is the guarantee that a foreign key value always points to a row that genuinely exists — a plain integer column only represents a relationship by convention; a real FOREIGN KEY constraint enforces it on every write.