liveBook · Manning

SQL trigger

As explained in PostgreSQL Mistakes and How to Avoid Them

A database trigger is a routine that executes automatically in response to specified events on a database object.

A SQL trigger is the safer, more predictable choice when a database-side action must respond automatically to changes on a table. It is especially preferable to a PostgreSQL rule when side effects must be controlled. section 5.2

Choose a trigger when rule rewriting creates operational ambiguity:

  • Rules rewrite the original query and can cause unintended side effects, such as incrementing a sequence more than once. section 5.2
  • Using VOLATILE functions with rules is risky because those functions may execute multiple times. section 5.2
  • Rules can alter an update with an added condition without preventing the original query from running, making their behavior difficult to reason about. section 5.2
  • Prefer triggers when behavior must be well-understood and predictable rather than dependent on query rewriting. section 5.2 section 5.7

Auditing order insertions

An insertion into erp.order_groups was intended to create an audit.audit_log row containing the new order ID, current role, and timestamp. A rule-based implementation rewrote the insertion and could evaluate nextval() again, producing unintended sequence advancement and misleading audit timing. A trigger is the appropriate alternative when this audit side effect must occur predictably. section 5.2

How PostgreSQL Mistakes and How to Avoid Them covers it

How deep it goes
Contrasts trigger predictability with rule rewriting, repeated VOLATILE calls, and updates that still execute; it does not implement trigger syntax.
Examples
Uses order insertion auditing and an old-order update rule to expose unintended effects and misleading prevention.
What you can do after
Evaluate when a PostgreSQL trigger is safer than a rule for predictable database-side behavior.
How it connects
Connects database rules, VOLATILE functions, sequence advancement, query rewriting, and audit logging.

Also explained in

Compare how 4 books explain SQL trigger →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of PostgreSQL Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.