Postgres equivalent of MySQL's ON UPDATE CURRENT_TIMESTAMP
I wanted an updated_at column that changes on every update, and the MySQL way to write it fails in Postgres:
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
ERROR: syntax error at or near "ON" (SQLSTATE 42601)
ON UPDATE CURRENT_TIMESTAMP is MySQL-only. In Postgres the column keeps just its default, and a trigger sets it before each update:
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- $$ quotes the function body, and plpgsql is Postgres's built-in procedural language.
CREATE OR REPLACE FUNCTION set_updated_at() RETURNS trigger AS $$
BEGIN
NEW.updated_at = CURRENT_TIMESTAMP; -- NEW is the row about to be written. This also replaces an updated_at your UPDATE statement set.
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER posts_set_updated_at
BEFORE UPDATE ON posts
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*) -- skip updates that write the same values back
EXECUTE FUNCTION set_updated_at();
The function and trigger work on an existing table too. Every table with an updated_at column can share the one function, but each needs its own CREATE TRIGGER. The CREATE TRIGGER docs cover the WHEN condition, and trigger functions in PL/pgSQL cover NEW and OLD.