Sub topic 9
Example: Keeping `updated_at` Current
Prerequisites and goal
Assume you know basic CREATE TABLE, INSERT, and UPDATE statements, and that you understand transactions. This example uses PL/pgSQL, PostgreSQL’s procedural language.
An updated_at column records when a row was last changed. A BEFORE UPDATE row trigger can set this value inside the database, so every application gets the same behavior.
The trigger function receives the row that PostgreSQL is about to write. It changes NEW.updated_at and returns NEW.
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();The trigger runs once for each row affected by an UPDATE. If one statement changes 500 rows, PostgreSQL calls the function 500 times.
How the row changes
For an update, the trigger function can use these records:
| Record | Meaning | Can the function change it? |
|---|---|---|
| `OLD` | The row before the update | No |
| `NEW` | The proposed row after the update | Yes, in a `BEFORE` trigger |
The function must return NEW for the modified row to continue through the update. Returning NULL from a BEFORE row trigger skips that row.
Limiting unnecessary work
The trigger above runs even when an update assigns values that are already present. A WHEN condition can avoid calling the function when no column value changed.
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();IS DISTINCT FROM handles NULL values safely. It compares the complete old and new rows.
You can also limit an update trigger to statements that mention a column:
CREATE TRIGGER accounts_balance_updated_at
BEFORE UPDATE OF balance ON accounts
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();UPDATE OF balance checks the columns named in the SET list. It does not check whether the value actually changed. For example, SET balance = balance still names balance, so the trigger can run.
A trigger is useful here because the rule applies no matter which client changes the table. Keep the function small, and remember that its work is part of the transaction. If the update rolls back, the timestamp change rolls back too.
Exercise
In a BEFORE UPDATE row trigger, which record should the function modify to refresh the timestamp, and what should it return?
Show answer
It should assign the new timestamp to NEW.updated_at and return NEW.