Video in progress
When do you use triggers, and what hidden problems do they bring?
Triggers are good for simple rules that must live with the data: updating updated_at, an audit record, a denormalized counter. But if business logic goes into triggers, it's invisible from the code, hard to test, and slows down the write path.
📖 Answer
I usually add only triggers like this:
CREATE FUNCTION touch_updated_at() RETURNS trigger AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER orders_touch
BEFORE UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION touch_updated_at();
This rule has to be enforced no matter which application or script does the writing, which is exactly the right place for a trigger.
Problems I've seen on prod:
- Invisibility. A new developer writes an
UPDATEand is surprised that something changed in another table. There's no trace of it in the code. - Chains. A trigger updates another table, its trigger updates a third one, and so on: one UPDATE becomes dozens of writes and unexpected locks.
- Slow batches.
FOR EACH ROWcalls the function a million times in a million-row UPDATE. SometimesFOR EACH STATEMENTwith a transition table (REFERENCING NEW TABLE AS ...) is much faster. - Hot row. A trigger that increments
shops.orders_counton every order creates a lock queue on a popular shop's row. - Hibernate. Hibernate doesn't know about the column the trigger changed, so the entity keeps a stale value, and you need
@Generatedor a refresh.
My rule: a trigger for data integrity, yes; for business flow (sending email, a state machine), no.
Sign up to mark studied questions and save your progress.