SQL · Queries that survive scale

How do triggers work and what are the risks?

Mediumtriggersauditingside effectsUpdated Oct 2026
Quiz this track

Short answer

A trigger runs database code automatically before or after an insert, update, or delete. They are useful for auditing and invariants, but hidden side effects make behavior harder to reason about.

A trigger is attached to a table and an event. Row-level triggers fire once per changed row; statement-level triggers fire once per statement. The trigger function can read OLD and NEW values and modify data, reject the change, or write to another table.

sql
CREATE FUNCTION audit_order_status() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  INSERT INTO order_status_audit (
    order_id, old_status, new_status, changed_at
  )
  VALUES (NEW.id, OLD.status, NEW.status, now());
  RETURN NEW;
END;
$$;

CREATE TRIGGER trg_order_status_audit
AFTER UPDATE OF status ON orders
FOR EACH ROW
EXECUTE FUNCTION audit_order_status();

Where triggers help and hurt

  • Audit trails that must capture every change regardless of application path
  • Maintaining a denormalized column inside the same transaction
  • Enforcing a complex invariant that cannot be expressed as a constraint
  • Hidden control flow that surprises developers reading only application code
  • Recursive or cascading triggers that are difficult to trace
  • Bulk operations where per-row work becomes a performance problem

Triggers run in the same transaction as the statement, so a failure rolls back the whole change. That is good for consistency but dangerous if the trigger performs slow or external work. Keep trigger logic small, deterministic, and well documented.

Prefer declarative constraints when they can express the rule. A trigger should be a deliberate exception, not the default place for business logic.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between a row-level and statement-level trigger?
  2. 2Can a trigger cause recursion?
  3. 3Why can triggers make debugging difficult?
  4. 4When is a constraint better than a trigger?

Say it in the interview

A trigger automatically runs database code on an insert, update, or delete. I use them for audit trails or invariants that must hold regardless of which application path writes the data. The risk is hidden side effects, recursion, and per-row overhead during bulk changes. I keep trigger logic small and prefer declarative constraints when they can express the same rule.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.