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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does the SQL touch?
- `on`, `notes`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.