Question presented to candidate: "What is a database trigger? Walk me through BEFORE versus AFTER, row-level versus statement-level, and tell me when you would and would not use one."
What a strong answer should cover:
- A trigger is code the database runs automatically when an
INSERT,UPDATEorDELETE(in PostgreSQL alsoTRUNCATE) happens on a table; nobody calls it, and it runs inside the same transaction as the statement - Timing:
BEFOREcan change or reject the incoming row (NEW),AFTERsees the final row and is used for audit logs and side tables,INSTEAD OFmakes views writable - Granularity:
FOR EACH ROWfires once per affected row withOLD/NEW;FOR EACH STATEMENTfires once per statement, even for zero rows (PostgreSQL; SQLite only has row triggers) - Good uses: audit trails,
updated_atstamps, keeping a denormalized counter or summary table in sync, enforcing a rule aCHECKcannot express - Costs: hidden logic that surprises readers, per-row overhead on bulk writes, cascades and recursion, ordering between several triggers, engine differences (MySQL error 1442)
Code / implementation expected: Optional β a small audit trigger with OLD / NEW, and an explanation of what fires when.
Schema used by the examples: