How can 'Triggers' be used in SQL, and what are the considerations?
Instruction: Describe the purpose of triggers and discuss important considerations when implementing them.
Context: This question explores the candidate's understanding of triggers for automating database actions and the careful planning required to use them effectively.
Updated
Official answer
A trigger runs database-defined logic in response to a specified event. Depending on the engine, triggers can run before or after a change, once per row or once per statement, and sometimes instead of an operation on a view.
A useful case is recording an old and new value in an audit table when a monitored field changes. Prefer a declarative constraint for an invariant it can express; a trigger makes behavior less visible to the statement's caller.
Check these boundaries:
- Handle zero-row and multirow statements correctly for the engine's trigger model.
- Avoid accidental recursion or cascading work, and include trigger cost when measuring write latency and locking.
- Define error behavior. In PostgreSQL, ordinary trigger work participates in the triggering transaction: a rollback removes its database audit rows too. This is not a log of every failed attempt.
- Do not assume an external email or HTTP request can be rolled back with the database. Durable, retryable integration needs an explicit design.
- Review privileges, document ordering dependencies, and test concurrent updates and failure paths.
Assessment: Explain why the trigger is appropriate, what transaction it belongs to, and how implicit work affects correctness and maintenance.