Skip to content

Instantly share code, notes, and snippets.

@colophonemes
Created January 5, 2017 04:58
Show Gist options
  • Save colophonemes/5880ac77ac8a5e355e7329dea6854282 to your computer and use it in GitHub Desktop.
Save colophonemes/5880ac77ac8a5e355e7329dea6854282 to your computer and use it in GitHub Desktop.
Postgres auto-updating timestamps

Auto-updating timestamps in Postgres

A Postgres function to change the updated_at column of a record on INSERT/UPDATE

-- The set_updated_at() function
CREATE FUNCTION set_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ language 'plpgsql';
-- Assigning the function as a TRIGGER on a table (e.g. mytable)
CREATE TRIGGER set_mytable_updated_at BEFORE UPDATE ON mytable FOR EACH ROW EXECUTE PROCEDURE set_updated_at()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment