1 Internal Workings of Triggers
TopBeyond the intermediate coverage, let's understand how triggers interact with the query execution pipeline.
Trigger Execution Context
A trigger executes within the same transaction as the statement that fired it. If the trigger fails, the entire statement rolls back. This means:
- Trigger errors cause the original INSERT/UPDATE/DELETE to fail
- Triggers see uncommitted data from the current transaction
- Triggers hold the same locks as the parent statement
- A ROLLBACK in the calling procedure also rolls back trigger actions
Multiple Triggers on the Same Event
-- You can have multiple triggers on the same event
CREATE TRIGGER trg_audit_first
BEFORE UPDATE ON orders
FOR EACH ROW
FOLLOWS trg_validate -- Execute AFTER trg_validate
BEGIN
-- Audit logic
END;
-- FOLLOWS / PRECEDES controls execution orderKey Takeaways
- Triggers run within the same transaction as the firing statement
- A trigger failure rolls back the entire statement
- Use
FOLLOWS/PRECEDESto control order when multiple triggers exist