Trigger Stamps Updated At On Change

A BEFORE UPDATE trigger rewrites NEW.updated_at inside the database, so every UPDATE gets a fresh timestamp even when the application forgets to set one.

SqlData Integrity

Code

snippet
-- updated_at is owned by the trigger: rows never miss their stamp even when the app layer forgets
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS trigger AS $$
BEGIN
    NEW.updated_at := now();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TABLE notes (
    id         integer PRIMARY KEY,
    body       text NOT NULL,
    updated_at timestamptz NOT NULL DEFAULT now()
);

-- PG 11+ syntax; older versions write EXECUTE PROCEDURE
CREATE TRIGGER notes_touch
BEFORE UPDATE ON notes
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();

INSERT INTO notes (id, body) VALUES (1, 'first draft');

UPDATE notes SET body = 'second draft' WHERE id = 1;

SELECT id, body, updated_at FROM notes;

What the code does

Several statements share this file — SELECT / INSERT / UPDATE / CREATE, with on and notes among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Applying it

The on table is the working surface here.

Statements that matter

CREATE TRIGGER notes_touch
BEFORE UPDATE ON notes
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();
UPDATE notes SET body = 'second draft' WHERE id = 1;
CREATE TABLE notes (
id         integer PRIMARY KEY,
body       text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`on`, `notes`.