3.3 Integrity Constraints & Referential Actions (CASCADE, SET NULL, RESTRICT)
π‘ Core Intuitionβ
π³ The Everyday Analogy: The Bank Account and Debit Cardsβ
Consider a central bank account and the debit cards linked to it.
- Domain Integrity: You cannot write "Three Hundred Dollars" in the ATM pin slot; it strictly expects four numeric digits.
- Entity Integrity: Every bank account must have a unique Account Number. You cannot open an account with "No Number" (
NULL). - Referential Integrity: A debit card cannot point to an account number that does not exist in the bank's central ledger.
- Referential Action Dilemma: What happens if the customer closes the bank account?
- Restrict: The bank prevents account closure until all linked cards are cancelled first.
- Cascade: Closing the account instantly and automatically terminates all linked cards.
- Set Null: The cards remain active in the system, but their account pointer is cleared (orphaned).
π» Bridging to Computer Scienceβ
Integrity Constraints are formal predicate conditions declared on a database schema that every legal database state must satisfy. They prevent accidental data corruption by rejecting any write, update, or delete transaction that breaks consistency rules.
π Core Deep-Dive & Conceptsβ
1. Classification of Relational Integrity Constraintsβ
Relational constraints operate across three hierarchical tiers:
A. Domain Constraintsβ
Domain constraints specify that the value of each attribute must be an atomic element from the physical domain .
- Data Type & Range: An
Agecolumn defined asTINYINT UNSIGNED CHECK (Age >= 18 AND Age <= 120). - Nullability: Declaring whether an attribute allows the non-value
NULL.
B. Entity Integrity Constraintβ
Rule: The Primary Key of any relation schema can never contain a NULL value.
Because the primary key serves as the unique identifier for individual real-world entities in the relation, allowing NULL would mean storing an entity whose identity is completely undefined.
C. Referential Integrity Constraintβ
Rule: Specified between two relations: a Referencing Relation (Child ) and a Referenced Relation (Parent ).
Every non-null value of the Foreign Key in the child relation must exist as a primary key value in the referenced parent relation .
2. The Comprehensive Operation Violation Matrixβ
When users execute INSERT, DELETE, or UPDATE operations on either the Parent table (PK side) or the Child table (FK side), referential integrity may be violated:
| Operation | Executed On Table | Can It Violate Referential Integrity? | Exact Architectural Reason |
|---|---|---|---|
| INSERT | Child Table () | YES (May Violate) | The inserted tuple may supply a Foreign Key value that does not exist in the Parent table. |
| INSERT | Parent Table () | NO (Never) | Adding a new primary key in the parent creates no invalid dangling references. |
| DELETE | Child Table () | NO (Never) | Removing a child row simply eliminates a reference; parent rows remain valid. |
| DELETE | Parent Table () | YES (May Violate) | Deleting a parent row leaves child rows referencing a non-existent primary key (orphans). |
| UPDATE | Child Table () | YES (May Violate) | Changing the value to a non-existent parent ID breaks referential integrity. |
| UPDATE | Parent Table () | YES (May Violate) | Modifying the value invalidates all child tuples pointing to the old value. |
3. Referential Actions on Parent Modificationβ
To maintain consistency when a tuple in the referenced Parent relation is deleted or its Primary Key is updated, the relational engine executes one of four declared Referential Actions:
FOREIGN KEY (Dept_Code) REFERENCES Department(Dept_Code)
ON DELETE [ CASCADE | SET NULL | SET DEFAULT | RESTRICT | NO ACTION ]
ON UPDATE [ CASCADE | SET NULL | SET DEFAULT | RESTRICT | NO ACTION ]
Detailed Breakdown of Policiesβ
1. CASCADE:
ON DELETE CASCADE: If parent rowDept_Code = 101is deleted, all student rows withDept_Code = 101are automatically purged from the child table.ON UPDATE CASCADE: If parentDept_Codechanges from101to201, the engine updates all referencing child rows to201simultaneously.
2. SET NULL:
- If the parent row is deleted or updated, the foreign key column in all matching child rows is set to
NULL. - Prerequisite: The child foreign key column must not be declared with a
NOT NULLconstraint; otherwise, the engine raises an integrity error.
3. RESTRICT / NO ACTION:
- The database engine actively checks whether any matching child records exist before permitting the parent modification. If even one matching child tuple exists, the entire transaction is aborted and rolled back.
4. SET DEFAULT:
- The child table's foreign key attributes are replaced with their specified default value (e.g.,
Dept_Code = 999forUnassigned).
4. Mathematical Proof: Foreign Key Set Differenceβ
Consider a database containing referencing relation and referenced relation , where attribute is a foreign key referencing primary key .
Because referential integrity strictly asserts that:
It follows directly from fundamental set theory that the set difference of foreign key values minus primary key values must evaluate to the empty set:
If a query returns any tuple, the database is in an illegal, corrupted state with orphaned records.
π Architecture / Visual Blueprintβ
π In The Real World: Production Case Studyβ
High-Volume Financial Ledgers at Stripe & Squareβ
In enterprise payment gateways, ledger entries record transactions moving money between customer accounts.
- The Architecture Rule: Payment records must never be deleted under any circumstance (
ON DELETE CASCADEis strictly prohibited on financial ledgers for auditing and regulatory compliance). - The Design Pattern:
CREATE TABLE ledger_transactions (
transaction_id UUID PRIMARY KEY,
account_id UUID NOT NULL,
amount NUMERIC(18, 4) NOT NULL,
status VARCHAR(20) NOT NULL,
CONSTRAINT fk_account
FOREIGN KEY (account_id)
REFERENCES user_accounts(account_id)
ON DELETE RESTRICT
ON UPDATE RESTRICT
); - Why RESTRICT? If a user attempts to delete their user account, the database rejects the command immediately because financial records reference that
account_id. Instead of physical row deletion, financial systems use Soft Deletion (setting anis_deleted = TRUEflag ordeleted_attimestamp).
π― Exam & Interview Pitfall Checkβ
Question 1: Why is an INSERT operation on the parent table guaranteed never to violate referential integrity, whereas an INSERT on the child table can?
Answer:
Referential integrity enforces . When you insert a tuple into the parent table, you are merely expanding the set of available target IDs (). Expanding the superset cannot cause an existing subset to fall outside of it. Conversely, inserting into the child table introduces a new element into . If this new ID does not exist in , the subset property is immediately broken.
Question 2: Under what condition will an ON DELETE SET NULL specification cause an execution error during parent row deletion?
Answer:
An ON DELETE SET NULL action will fail and trigger a database constraint violation error if the foreign key column in the child table was also declared with a NOT NULL constraint (e.g. Dept_Code INT NOT NULL REFERENCES Department(Dept_Code)). The engine cannot write NULL to a column that explicitly prohibits null values.
Trap 1: "Is referential integrity specified on an individual table or between tables?"
Answer: Entity integrity is specified on an individual table (e.g., Primary Key), but Referential Integrity is an inter-relational constraint specified between two tables (or within one table in the case of a recursive foreign key).
Trap 2: "What is the difference between RESTRICT and NO ACTION in SQL standard?"
Answer: In standard SQL, both prevent the deletion or update of a referenced parent row. However, RESTRICT enforces the check immediately before executing any statement. NO ACTION allows deferred constraint checking (if declared as DEFERRABLE INITIALLY DEFERRED), meaning foreign key validity is checked at the end of the transaction rather than immediately after the individual statement.