Skip to content
GreenSnippets

Automatically maintain an updated_at column

A reusable PostgreSQL trigger function that sets updated_at to now() on every UPDATE.

SQL
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  NEW.updated_at := now();
  RETURN NEW;
END;
$$;

CREATE TRIGGER articles_set_updated_at
  BEFORE UPDATE ON articles
  FOR EACH ROW
  EXECUTE FUNCTION set_updated_at();

Example / expected output

Output
-- UPDATE articles SET title = 'New' WHERE id = 1;  -- updated_at changes automatically

How it works

Relying on application code to set updated_at is easy to forget. One trigger function can be attached to any table with that column. BEFORE UPDATE lets the function change the new row before it is written.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.