← Back to SQL, page 13

sql-0242 · Medium mid

What are the risks of putting business logic in triggers?

Triggers run implicitly, so developers reading application code do not see them, and bulk operations can behave unexpectedly slowly. Chains of triggers are hard to debug and test, ordering among several triggers can surprise, and logic is split between the database and the application. They remain a good fit for small, always-true rules: audit rows, timestamps and derived counters.

Full answer

Problems teams run into:

  • Hidden behaviour. A one-row UPDATE in code silently performs five writes.
  • Performance. Row-level triggers run once per row, so a 1-million-row update fires a million times.
  • Cascades. Trigger A updates table B, whose trigger updates table C, and an error surfaces far from its cause.
  • Testing and deployment. Trigger code lives in migrations and is often missed by code review and unit tests.
  • External side effects. Sending email or calling an API from a trigger cannot be rolled back with the transaction.

Good uses: auditing, maintaining updated_at, keeping a denormalized counter in sync, and enforcing rules that must hold no matter which client writes.

A middle path is to keep the rule in the database but make it visible: name triggers clearly, keep each one short, and list them in the schema documentation. For side effects, write an outbox row in the trigger and let a separate worker act on it after commit.

Key points

  • Triggers hide behaviour from application readers
  • Row-level triggers multiply work on bulk writes
  • Trigger chains are hard to debug
  • Use them for audits, timestamps and invariants
  • Use an outbox for side effects

Common mistakes

  • Sending notifications from inside a trigger
  • Building workflows out of chained triggers

Follow-ups

  • What is the transactional outbox pattern?
  • How would you test trigger behaviour?

Tips

  • Give both risks and legitimate uses