Sub topic 7
Reading NEW, OLD, and TG_* variables
This chapter assumes you can write a basic PL/pgSQL trigger function and attach it with CREATE TRIGGER. It covers what a trigger function can read when it runs, and the mistakes people make when reading it.
What PostgreSQL gives a trigger function
A trigger function takes no parameters. PostgreSQL instead creates special variables in its scope before the first statement runs. They fall into two groups:
- Row variables
NEWandOLDhold the row being written and the row as it was before. - Context variables with a
TG_prefix describe which trigger fired and why.
NEW and OLD
NEW holds the row that will be stored. OLD holds the row as it existed before the change. Both have the row type of the table, so you read columns with NEW.price or OLD.email. Which one exists depends on the event and the trigger level.
| Event | NEW | OLD |
|---|---|---|
| INSERT, row-level | the new row | not assigned |
| UPDATE, row-level | the updated row | the row before the update |
| DELETE, row-level | not assigned | the deleted row |
| TRUNCATE | not assigned | not assigned |
| Any statement-level trigger | null | null |
Three rules follow from this table.
- In a
BEFORErow trigger,NEWis writable. AssigningNEW.updated_at := now()and returningNEWchanges what is stored. - In an
AFTERrow trigger, changingNEWdoes nothing, because the row is already written.NEWshows the final stored values, including changes made byBEFOREtriggers and column defaults. - In a
BEFORE INSERTtrigger,NEWalready contains defaults such as identity values andDEFAULT now(). You can read the generatedidthere.
Statement-level triggers have no row variables. To see the affected rows from such a trigger, use a transition table (covered in a later chapter).
The TG_* variables
| Variable | Type | Contents |
|---|---|---|
| `TG_NAME` | name | the trigger's name |
| `TG_WHEN` | text | `BEFORE`, `AFTER`, or `INSTEAD OF` |
| `TG_LEVEL` | text | `ROW` or `STATEMENT` |
| `TG_OP` | text | `INSERT`, `UPDATE`, `DELETE`, or `TRUNCATE` |
| `TG_RELID` | oid | object ID of the table or view |
| `TG_TABLE_NAME` | name | table name, without schema |
| `TG_TABLE_SCHEMA` | name | schema of the table |
| `TG_NARGS` | integer | number of arguments given in `CREATE TRIGGER` |
| `TG_ARGV[]` | text[] | those arguments, counting from 0 |
Older code may use TG_RELNAME. Use TG_TABLE_NAME instead.
Seeing the variables in action
This setup prints the context of every row-level event. The trigger is AFTER, so the NULL return value is harmless. In a BEFORE row trigger, returning NULL would skip the operation.
CREATE TABLE items (
id int PRIMARY KEY,
name text,
price numeric,
updated_at timestamptz
);
CREATE FUNCTION show_context() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'trigger=% when=% level=% op=% table=%.% nargs=% argv=%',
TG_NAME, TG_WHEN, TG_LEVEL, TG_OP,
TG_TABLE_SCHEMA, TG_TABLE_NAME, TG_NARGS, TG_ARGV;
IF TG_OP IN ('UPDATE', 'DELETE') THEN
RAISE NOTICE 'OLD = %', OLD;
END IF;
IF TG_OP IN ('INSERT', 'UPDATE') THEN
RAISE NOTICE 'NEW = %', NEW;
END IF;
RETURN NULL;
END;
$$;
CREATE TRIGGER items_show
AFTER INSERT OR UPDATE OR DELETE ON items
FOR EACH ROW
EXECUTE FUNCTION show_context('first', 'second');
INSERT INTO items (id, name, price) VALUES (1, 'pen', 2.50);
UPDATE items SET price = 3.00 WHERE id = 1;
DELETE FROM items WHERE id = 1;The INSERT should print notices like these:
NOTICE: trigger=items_show when=AFTER level=ROW op=INSERT table=public.items nargs=2 argv={first,second}
NOTICE: NEW = (1,pen,2.50,)The update prints both OLD and NEW, and the delete prints only OLD. A null column appears as an empty field inside the row text.
Guard row variables by TG_OP
One function can serve several events, but it must not read a row variable that was never assigned. Doing so raises an error when the statement runs. Branch on TG_OP first, and nest the checks.
CREATE FUNCTION log_price_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'UPDATE' THEN
IF NEW.price IS DISTINCT FROM OLD.price THEN
RAISE NOTICE 'item % price: % -> %', NEW.id, OLD.price, NEW.price;
END IF;
END IF;
RETURN NULL;
END;
$$;Do not write IF TG_OP = 'UPDATE' AND NEW.price <> OLD.price. PostgreSQL does not promise to stop evaluating at the first false operand, so the OLD reference could still run on an insert. Use IS DISTINCT FROM instead of <> so that null values compare correctly.
Arguments through TG_ARGV
Arguments in CREATE TRIGGER let one function serve many tables or columns. PostgreSQL passes every argument as a string, even if you write a number. The next function stamps whichever column you name:
CREATE FUNCTION stamp_column() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_NARGS <> 1 THEN
RAISE EXCEPTION 'stamp_column needs one column name, got % arguments', TG_NARGS;
END IF;
NEW := jsonb_populate_record(NEW, jsonb_build_object(TG_ARGV[0], now()));
RETURN NEW;
END;
$$;
CREATE TRIGGER items_stamp
BEFORE UPDATE ON items
FOR EACH ROW
EXECUTE FUNCTION stamp_column('updated_at');PL/pgSQL cannot write NEW.<name> with a name held in a variable, so the function builds a JSON object and merges it into NEW. Here TG_NARGS validates the argument count, and TG_ARGV[0] is the first argument because the array starts at 0.
Using TG_RELID and TG_TABLE_NAME
TG_TABLE_NAME gives only the bare name. If the same function is attached to tables in different schemas, combine TG_TABLE_SCHEMA and TG_TABLE_NAME. You can also cast TG_RELID::regclass, which produces a correctly quoted, schema-qualified name when needed. In an audit table, store one of these rather than the bare name, so rows from different schemas stay distinguishable.
Common errors
- Reading
OLDin an insert trigger, orNEWin a delete trigger. The variable is unassigned, and the statement fails. Guard withTG_OP. - Assigning to
NEWin anAFTERtrigger. It compiles and runs, but the stored row does not change. - Expecting
NEWin a statement-level trigger. It is null there. Use a transition table, or make the trigger row-level. - Comparing with
=or<>. If either side is null, the result is null and the condition acts as false. UseIS DISTINCT FROM. - Treating
TG_ARGVas typed. Cast explicitly, for exampleTG_ARGV[0]::numeric.
Exercise
A single trigger function is attached as AFTER INSERT OR DELETE ... FOR EACH ROW with EXECUTE FUNCTION audit_row('orders', 'v2'). Which row variable is available for each event, what does TG_ARGV[1] return, and what does TG_NARGS return?
Show answer
For INSERT only NEW is assigned, and for DELETE only OLD is assigned, so the function should branch on TGOP before reading either. TGARGV[1] is the text 'v2', because the array is zero-based and the first argument 'orders' is at index 0. TG_NARGS is 2.
Exercise
A BEFORE UPDATE trigger function sets NEW.updated_at := now(); but ends with RETURN OLD;. What gets stored, and why?
Show answer
The old row values are stored, including the old updated_at. The row returned from a BEFORE row trigger is the one written, and the assignment to NEW is discarded because NEW is not returned.