Sub topic 13
Writing Trigger Functions
Assume you know basic INSERT, UPDATE, and DELETE statements, PostgreSQL tables, and PL/pgSQL blocks. This chapter focuses on how trigger functions receive row information and how PostgreSQL calls them.
A trigger function is a special PL/pgSQL function that runs automatically when an event occurs on a table or view. The event can be an INSERT, UPDATE, or DELETE. You connect the function to an event with CREATE TRIGGER.
The trigger function contract
A trigger function must:
- Return
trigger. - Use no ordinary function parameters.
- Return the correct row value for its trigger timing.
- Use special variables supplied by PostgreSQL.
The most important special variables are:
NEW: the row after an insert or update.OLD: the row before an update or delete.TG_OP: the operation name, such as'INSERT','UPDATE', or'DELETE'.TG_WHEN: the timing, either'BEFORE'or'AFTER'.TG_LEVEL: either'ROW'or'STATEMENT'.
A row-level trigger runs once for each affected row. A statement-level trigger runs once for the whole SQL statement.
Changing `NEW` in a `BEFORE` trigger
A BEFORE row trigger can validate or modify the row before PostgreSQL stores it. The function must return NEW to allow the operation to continue.
This example updates a timestamp whenever an order changes:
CREATE TABLE orders (
id integer PRIMARY KEY,
total numeric NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION set_orders_updated_at()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
IF TG_OP = 'UPDATE' THEN
NEW.updated_at := now();
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER orders_updated_at
BEFORE UPDATE ON orders
FOR EACH ROW
EXECUTE FUNCTION set_orders_updated_at();
INSERT INTO orders (id, total) VALUES (1, 125.00);
UPDATE orders SET total = 150.00 WHERE id = 1;
SELECT * FROM orders;Returning NULL from a BEFORE row trigger skips the current row operation. This can silently prevent an insert, update, or delete, so use it only when that behavior is intentional.
Using `OLD` and `NEW`
For an insert, only NEW exists. For a delete, only OLD exists. For an update, both exist. A single trigger function can handle all three operations:
CREATE TABLE order_changes (
order_id integer NOT NULL,
operation text NOT NULL,
changed_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION log_order_changes()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
IF TG_OP = 'DELETE' THEN
INSERT INTO order_changes (order_id, operation)
VALUES (OLD.id, TG_OP);
RETURN OLD;
ELSE
INSERT INTO order_changes (order_id, operation)
VALUES (NEW.id, TG_OP);
RETURN NEW;
END IF;
END;
$$;
CREATE TRIGGER orders_change_log
AFTER INSERT OR UPDATE OR DELETE ON orders
FOR EACH ROW
EXECUTE FUNCTION log_order_changes();For an AFTER trigger, PostgreSQL ignores the returned row value, but returning NEW or OLD keeps the function clear and valid. An AFTER trigger is useful for logging or related work after the original operation succeeds.
Testing and common errors
Test each event separately. Check that an update changes updated_at, that a delete logs OLD.id, and that a failed statement does not leave partial trigger effects. Trigger actions normally run in the same transaction as the original statement.
Common mistakes include:
- Declaring
RETURNS integerinstead ofRETURNS trigger. - Reading
OLDduring an insert. - Reading
NEWduring a delete. - Forgetting
FOR EACH ROWwhen row data is required. - Using a trigger to enforce a rule that a
CHECKconstraint or foreign key could enforce more simply.
Exercise
In a BEFORE DELETE FOR EACH ROW trigger, which row variable contains the row being removed, and what should the function usually return?
Show answer
OLD contains the row being removed. The function should usually return OLD to allow the delete to continue.