Trigger recursion and ordering
Overview
Trigger actions can fire further triggers. A recursive cycle can cause repeated writes or reach a depth limit. A terminating predicate is safer than relying on a recursion setting or an arbitrary maximum depth. PostgreSQL fires multiple triggers of the same kind for the same event in alphabetical name order; do not assume that ordering rule in SQLite.
First example
BEGIN;UPDATE tr_label SET label=' beta ' WHERE id=1;SELECT label,(SELECT COUNT(*) FROM tr_trace) FROM tr_label;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ "beta", 1 ]]How it works
The fixture explicitly enables recursive_triggers. Its label trigger trims surrounding spaces only when NEW.label differs from trim(NEW.label). The nested update reaches a fixed point, so the guard is false and no further normalization occurs. The trace table records the single normalization action. The first example changes a label to padded text, the second writes already normalized text. This is a deliberately small deterministic case, not a general recursion detector. PostgreSQL can normalize NEW directly in a BEFORE row trigger, avoiding a second UPDATE. Prefer one coherent trigger when actions must run in a particular order, document dependencies, and test chained effects. Do not disable all triggers to fix a cycle without assessing integrity.
Practical example
BEGIN;UPDATE tr_label SET label='beta' WHERE id=1;SELECT label,(SELECT COUNT(*) FROM tr_trace) FROM tr_label;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ "beta", 0 ]]Practice and mistakes
Practice: change label to three spaces. Hint 1: trim yields the empty string, which this fixture permits. Hint 2: expect one trace and then termination. Consider whether a NOT NULL or CHECK rule should reject empty labels in a real schema. Roll back.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE TABLE tr_pg_label(id integer PRIMARY KEY,label text NOT NULL);INSERT INTO tr_pg_label VALUES(1,'alpha');CREATE FUNCTION tr_pg_trim() RETURNS trigger LANGUAGE plpgsql AS $$BEGIN NEW.label := btrim(NEW.label); RETURN NEW;END;$$;CREATE TRIGGER tr_pg_normalize BEFORE UPDATE OF label ON tr_pg_label FOR EACH ROW EXECUTE FUNCTION tr_pg_trim();UPDATE tr_pg_label SET label=' beta ' WHERE id=1;SELECT label FROM tr_pg_label;ROLLBACK;Expected result, not executed: [["beta"]]