← Back to SQL, page 13

sql-0241 · Medium mid

Write a PostgreSQL trigger that keeps an updated_at column current on every UPDATE.

Create a PL/pgSQL function that sets NEW.updated_at = now() and returns NEW, then attach it with CREATE TRIGGER ... BEFORE UPDATE ... FOR EACH ROW. A BEFORE trigger can change the row before it is written, while in SQLite an AFTER UPDATE trigger that runs an UPDATE on the same row does the same job.

Full answer
sql
CREATE TABLE items (id int PRIMARY KEY, name text, updated_at timestamptz DEFAULT '2026-01-01');
CREATE FUNCTION touch() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  NEW.updated_at := TIMESTAMPTZ '2026-03-01 00:00:00+00';
  RETURN NEW;
END $$;
CREATE TRIGGER items_touch BEFORE UPDATE ON items FOR EACH ROW EXECUTE FUNCTION touch();
INSERT INTO items (id, name) VALUES (1, 'pen');
UPDATE items SET name = 'blue pen' WHERE id = 1;
SELECT id, name, updated_at > TIMESTAMPTZ '2026-01-01 00:00:00+00' AS touched FROM items;
idnametouched
1blue pentrue

The sample function writes a fixed timestamp instead of now() so the output is stable. The BEFORE trigger changed the row in flight, so the update and the new timestamp were written together. Returning NULL from a BEFORE row trigger would skip the write entirely.

SQLite has no trigger functions; the usual form is:

sql
CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, updated_at TEXT DEFAULT '2026-01-01');
CREATE TRIGGER items_touch AFTER UPDATE ON items
WHEN NEW.updated_at IS OLD.updated_at
BEGIN
  UPDATE items SET updated_at = '2026-03-01' WHERE id = NEW.id;
END;
INSERT INTO items (id, name) VALUES (1, 'pen');
UPDATE items SET name = 'blue pen' WHERE id = 1;
SELECT id, name, updated_at FROM items;
idnameupdated_at
1blue pen2026-03-01

The SQLite trigger runs a second UPDATE. It does not loop, because recursive triggers are off by default, and the WHEN guard means the inner update does not fire it again even if they were on.

sql
CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, updated_at TEXT DEFAULT '2026-01-01');
CREATE TRIGGER items_touch AFTER UPDATE ON items
WHEN NEW.updated_at IS OLD.updated_at
BEGIN
  UPDATE items SET updated_at = '2026-03-01' WHERE id = NEW.id;
END;
INSERT INTO items (id, name) VALUES (1, 'pen');
UPDATE items SET name = 'blue pen' WHERE id = 1;
SELECT id, name, updated_at FROM items;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • PostgreSQL triggers call a trigger function
  • BEFORE row triggers can modify NEW
  • Return NEW to write the row, NULL to skip it
  • SQLite uses an AFTER trigger with an UPDATE

Common mistakes

  • Using an AFTER trigger in PostgreSQL to modify NEW
  • Writing a SQLite trigger that recursively fires itself

Follow-ups

  • How would you skip updates that change nothing?
  • What does FOR EACH STATEMENT do?

Tips

  • Explain why BEFORE is the right timing