created_at records when a row was inserted; updated_at records when it last
changed. Both belong on almost every table. updated_at requires a trigger to
stay current; without one it reflects insert time only and never changes.
Postgres
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()Always use TIMESTAMPTZ, never TIMESTAMP. TIMESTAMP silently drops the timezone
offset; TIMESTAMPTZ stores UTC and converts on read. Mixing the two causes subtle
bugs when clients are in different timezones.
DEFAULT now() fires at insert time. Mark both columns NOT NULL; a row without a
creation time is always a bug.
updated_at trigger
Define the trigger function once per database and wire it to every table that needs it:
CREATE FUNCTION set_updated_at()
RETURNS TRIGGER
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$;
CREATE TRIGGER posts_set_updated_at
BEFORE UPDATE ON posts
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();SQLite
SQLite has no native date type. The two idiomatic choices:
TEXT: ISO-8601 strings ('2024-01-15T09:30:00Z'). Human-readable in a DB browser; sorts correctly as text.INTEGER: Unix epoch seconds. Easier arithmetic; smaller storage.
TEXT is the better default unless you need to do a lot of date math in SQL.
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))updated_at trigger
SQLite triggers use a different syntax from Postgres; they UPDATE the row rather
than rewriting NEW:
CREATE TRIGGER posts_set_updated_at
AFTER UPDATE ON posts
BEGIN
UPDATE posts SET updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
WHERE id = NEW.id;
END;The trigger’s own UPDATE does not re-fire it while PRAGMA recursive_triggers
is off, which is the default.