Question presented to candidate: "When you declare a foreign key you can add ON DELETE and ON UPDATE actions. What options exist, what does each one do to the child rows, and how do you pick one for a given relationship?"
What a strong answer should cover:
- The five referential actions:
NO ACTION(the default),RESTRICT,CASCADE,SET NULL,SET DEFAULT, each set separately forON DELETEandON UPDATE NO ACTIONvsRESTRICT: both refuse to orphan a child, butNO ACTIONis checked at the end of the statement (or at commit when the constraint is deferred), whileRESTRICTis checked immediately and cannot be deferred- Choosing by ownership: owned children (addresses, line items) cascade; records with their own value (orders, invoices) restrict; history that outlives the parent uses
SET NULLorSET DEFAULTto a placeholder - Engine differences: SQLite enforces foreign keys only after
PRAGMA foreign_keys = ON; MySQL InnoDB treatsNO ACTIONasRESTRICTand rejectsSET DEFAULT; SQL Server has noRESTRICTkeyword - Operational points: PostgreSQL does not index the referencing column automatically, so cascades and checks on large child tables need an index; cascades can delete far more than expected
Code / implementation expected: Yes β a schema with different actions per child table and a delete or update that shows each one.
Schema used by the examples: