Sub topic 5
FOR EACH ROW vs FOR EACH STATEMENT
This chapter assumes you can write a trigger function and attach it with CREATE TRIGGER, and that you know BEFORE and AFTER timing. Here you learn the last required part of the trigger definition: how many times the function runs for one SQL command.
The two granularities
A trigger's granularity decides how often PostgreSQL calls the trigger function.
FOR EACH ROWcalls the function once for every row the statement inserts, updates, or deletes.FOR EACH STATEMENTcalls the function once per SQL statement, regardless of how many rows it touches.
If you omit the clause, PostgreSQL uses FOR EACH STATEMENT. Most trigger tutorials show row triggers, so people often forget that default.
| Property | FOR EACH ROW | FOR EACH STATEMENT |
|---|---|---|
| Calls per statement | One per affected row | Exactly one |
| Fires when 0 rows match | No | Yes |
| `NEW` and `OLD` | Available (depending on event) | Not available |
| Return value | Matters in BEFORE triggers | Ignored |
| Events | INSERT, UPDATE, DELETE | INSERT, UPDATE, DELETE, TRUNCATE |
| Timing | BEFORE, AFTER, INSTEAD OF (views) | BEFORE, AFTER |
| `WHEN` condition may use columns | Yes | No |
Seeing the firing order
The following script attaches four triggers to one table. All four use the same function, which reports TG_WHEN, TG_LEVEL, and TG_OP. These are built-in variables that describe how the trigger fired.
CREATE TABLE items (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
CREATE FUNCTION trace_trigger() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE '% % %', TG_WHEN, TG_LEVEL, TG_OP;
IF TG_LEVEL = 'ROW' AND TG_WHEN = 'BEFORE' THEN
RETURN NEW; -- a BEFORE row trigger must return the row to keep it
END IF;
RETURN NULL; -- ignored in the remaining cases
END;
$$;
CREATE TRIGGER items_before_stmt BEFORE INSERT OR UPDATE ON items
FOR EACH STATEMENT EXECUTE FUNCTION trace_trigger();
CREATE TRIGGER items_before_row BEFORE INSERT OR UPDATE ON items
FOR EACH ROW EXECUTE FUNCTION trace_trigger();
CREATE TRIGGER items_after_row AFTER INSERT OR UPDATE ON items
FOR EACH ROW EXECUTE FUNCTION trace_trigger();
CREATE TRIGGER items_after_stmt AFTER INSERT OR UPDATE ON items
FOR EACH STATEMENT EXECUTE FUNCTION trace_trigger();
INSERT INTO items (name) VALUES ('a'), ('b');The INSERT of two rows prints:
NOTICE: BEFORE STATEMENT INSERT
NOTICE: BEFORE ROW INSERT
NOTICE: BEFORE ROW INSERT
NOTICE: AFTER ROW INSERT
NOTICE: AFTER ROW INSERT
NOTICE: AFTER STATEMENT INSERTThe statement triggers run once, at the start and end. The row triggers run twice each. The sequence is the same for every statement.
AFTER row triggers do not run immediately after each row is written. PostgreSQL queues them and runs them when the statement has processed all its rows, just before the AFTER statement triggers. Because of this, an AFTER row trigger can see the effects of rows written later in the same statement.
Zero rows still fires a statement trigger
A statement trigger fires even when nothing changes:
UPDATE items SET name = 'x' WHERE false;NOTICE: BEFORE STATEMENT UPDATE
NOTICE: AFTER STATEMENT UPDATENo row trigger fires, because there are no rows. If a statement trigger needs to know whether anything changed, it must check for itself. A transition table (a later chapter) lets it count the affected rows.
A related case is INSERT ... ON CONFLICT DO UPDATE. Both the INSERT and the UPDATE statement triggers fire, even if every row ends up taking only one of the two paths.
What a statement trigger cannot do
Statement triggers have no current row. Do not use NEW or OLD in them. The return value is ignored, so return NULL by convention. A BEFORE statement trigger can still stop the command by raising an exception.
The WHEN condition of a statement trigger cannot refer to column values, since there is no row to read.
TRUNCATE is the one event that exists only at statement level. A statement trigger is the way to guard against it:
CREATE FUNCTION forbid_truncate() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'TRUNCATE on % is not allowed', TG_TABLE_NAME;
END;
$$;
CREATE TRIGGER items_no_truncate
BEFORE TRUNCATE ON items
FOR EACH STATEMENT
EXECUTE FUNCTION forbid_truncate();TRUNCATE items; now fails with the message you wrote. A row-level DELETE trigger cannot do this job, because TRUNCATE does not scan rows and never fires one.
Choosing between them
Use a row trigger when the logic depends on each row's values:
- Setting
updated_aton the row being written. - Validating
NEW.balance. - Writing one audit record per changed row.
Use a statement trigger when the logic concerns the command as a whole:
- Blocking
TRUNCATE. - Logging that a bulk operation happened.
- Refreshing a summary table once after a large load.
- Processing all changed rows in one set-based query, using a transition table.
The cost difference is real. A row trigger on a 1,000,000-row UPDATE makes 1,000,000 function calls, and each call has its own overhead. A single statement trigger with a transition table can do the same work in one INSERT ... SELECT, which is often much faster.
Common errors
- "record NEW is not assigned yet" or null-valued fields. Your function reads
NEWorOLDbut is attached asFOR EACH STATEMENT. AddFOR EACH ROW, or rewrite the function to use a transition table. - Rows silently vanish. A BEFORE row trigger returned
NULL, which skips that row without an error. ReturnNEWfor INSERT and UPDATE. TheRETURN NULLin the example above is safe only because the other three triggers ignore their return value. - A trigger never fires on an empty statement. This applies to row triggers only. Statement triggers do fire, so if you expected silence, check the granularity.
- Surprise call counts.
INSERT ... SELECTwith 10,000 source rows makes 10,000 row-trigger calls. Check for expensive work inside row triggers.
Exercise
A table has an AFTER DELETE trigger defined FOR EACH STATEMENT. You run DELETE FROM items WHERE id = -1, which matches no rows. How many times does the trigger function run, and can it read OLD? How would the answer change if the trigger were FOR EACH ROW?
Show answer
The statement trigger runs exactly once, even though no rows were deleted, and it cannot read OLD because statement triggers have no current row. With FOR EACH ROW the function would run zero times, because no rows were affected.
Exercise
You must prevent anyone from running TRUNCATE on a table, and you also want to log every deleted row. Which granularity do you use for each requirement, and why?
Show answer
Use a BEFORE TRUNCATE trigger FOR EACH STATEMENT that raises an exception, because TRUNCATE is only available at statement level. Use an AFTER DELETE trigger FOR EACH ROW to log each deleted row, because it can read OLD for every row. A statement trigger has no OLD record unless you add a transition table.