Sub topic 9
Example: keeping updated_at current
This chapter builds one of the most common triggers in practice: a column that records when a row last changed. It assumes you can write basic CREATE TABLE and UPDATE statements. It also assumes you know the shape of a trigger function (a function that RETURNS trigger) and the CREATE TRIGGER syntax from the earlier chapters.
Why a trigger fits this job
An updated_at column is only useful if it is always right. If each application sets it by hand, one forgotten code path, one manual fix in psql, or one batch script leaves stale values. A default expression such as DEFAULT now() handles inserts but does nothing on updates. A trigger runs inside the database for every update, whichever client sent it.
The job needs a BEFORE trigger. The row is not yet stored, so the function can change NEW and return it. An AFTER trigger could only issue a second UPDATE, which writes the row twice and fires triggers again.
The table and the trigger function
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
balance numeric(12,2) NOT NULL DEFAULT 0,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER accounts_set_updated_at
BEFORE UPDATE ON accounts
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();Three details matter here:
FOR EACH ROWmakes the function run once per updated row, and only row-level triggers have aNEWrecord to change.- The assignment
NEW.updated_at := now()edits the row that is about to be stored. RETURN NEWhands that edited row back to the executor. ReturningNULLfrom aBEFORErow trigger would silently skip the update for that row, which is a common mistake.
Inserts need no trigger. The column default already sets the value when a row is created.
Trying it
INSERT INTO accounts (email) VALUES ('[email protected]');
UPDATE accounts SET balance = 50 WHERE email = '[email protected]';
-- The client tries to set its own value. The trigger overwrites it.
UPDATE accounts
SET updated_at = '2000-01-01'
WHERE email = '[email protected]';
SELECT email, updated_at > '2000-01-01' AS overwritten
FROM accounts;The last query returns true. The trigger runs after the SET list is applied, so it has the final word. This is usually what you want, because clients can no longer forge the timestamp. If you need to allow explicit values, such as during a data import, test for them inside the function or disable the trigger for that session (see the chapter on managing triggers).
Which clock: now() or clock_timestamp()
now() returns the start time of the current transaction. It does not advance while the transaction runs.
BEGIN;
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
SELECT pg_sleep(2);
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
SELECT updated_at = now() AS same_as_txn_start FROM accounts WHERE id = 1;
COMMIT;The query returns true, even though the second update ran two seconds later. All rows touched in one transaction get the same value. That is often desirable, since it marks which rows changed together, and it keeps values consistent with other now() defaults in the same transaction.
If you need the real wall-clock moment of each change, use clock_timestamp() in the function instead. Be aware of the trade-off: timestamps within a transaction then differ, and they no longer match now().
Skipping updates that change nothing
The first version fires for every UPDATE, including one that writes back the same values:
UPDATE accounts SET balance = balance WHERE id = 1;The row is "modified" from the trigger's point of view, so updated_at moves although no data changed. If that is wrong for your application, add a WHEN condition. CREATE OR REPLACE TRIGGER needs PostgreSQL 14 or later. On older versions, use DROP TRIGGER and then CREATE TRIGGER.
CREATE OR REPLACE TRIGGER accounts_set_updated_at
BEFORE UPDATE ON accounts
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE FUNCTION set_updated_at();OLD.* IS DISTINCT FROM NEW.* compares the two whole rows and treats NULL values as comparable. When the rows are equal, PostgreSQL skips the function call entirely, which also saves the cost of invoking PL/pgSQL.
Two edge cases:
- The comparison needs an equality operator for every column type. A
jsoncolumn has none, so the trigger fails with an operator error when it fires. Usejsonb, or compare selected columns instead of whole rows. - A
WHENcondition on aBEFOREtrigger cannot refer to system columns, and it cannot useOLDorNEWinINSERT-only orDELETE-only triggers where that record does not exist.
One function for many tables
The function never mentions accounts. It only needs a column named updated_at, so you can attach it to any table that has one:
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TRIGGER products_set_updated_at
BEFORE UPDATE ON products
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();If you attach it to a table without that column, the first update fails with an error such as record "new" has no field "updated_at". The error appears at run time, not when you create the trigger, so test each new attachment with a real UPDATE.
Interaction with other triggers
Several BEFORE triggers on one table fire in alphabetical order by trigger name, and each receives the NEW row that the previous one returned. A validation trigger that reads NEW.balance is unaffected by the timestamp trigger. A trigger that depends on NEW.updated_at having the final value should sort after accounts_set_updated_at. Choose names deliberately if order matters.
Common mistakes
- Creating the trigger as
AFTER UPDATEand assigning toNEW. The assignment has no effect, because anAFTERrow trigger's return value is ignored and the row is already stored. - Forgetting
RETURN NEW, which makes PL/pgSQL raise an error at the end of the function, or returningNULL, which drops the update. - Running an
UPDATEinside the function to set the column. This fires the trigger again and recurses. - Expecting the trigger to run on
INSERTorTRUNCATE. It fires only for the events listed inCREATE TRIGGER.
Exercise
A table tasks has columns id, title, done boolean and updated_at timestamptz. You attach set_updated_at() as a BEFORE UPDATE ... FOR EACH ROW trigger. You want updated_at to change only when done changes, not when title is edited. Which trigger clause achieves this, and why must the trigger still be BEFORE?
Show answer
Add WHEN (OLD.done IS DISTINCT FROM NEW.done) to the trigger. This skips the function when done has the same value (including both NULL). The trigger must be BEFORE because only a BEFORE row trigger can modify NEW.updated_at and have the changed row stored. An AFTER trigger's return value is ignored and the row is already written.
Exercise
Inside one transaction you update 100 rows, with a two-second pause between the first and last update. All 100 rows end up with the same updated_at. Why, and what change to the function would give each row its own time?
Show answer
now() returns the transaction's start time, so every call in that transaction returns the same value. Replacing now() with clock_timestamp() in set_updated_at() returns the actual current time at each call, so the rows get different values.