Skip to content

Instantly share code, notes, and snippets.

@sscovil
Created January 25, 2022 16:41
Show Gist options
  • Save sscovil/137d36a023bd51e71c660d21bf015f8e to your computer and use it in GitHub Desktop.
Save sscovil/137d36a023bd51e71c660d21bf015f8e to your computer and use it in GitHub Desktop.
Example of update trigger to set updated_at to current timestamp
CREATE TABLE IF NOT EXISTS foobar (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
created_at TIMESTAMPTZ NOT NULL DEFAULT timezone('utc', now()),
updated_at TIMESTAMPTZ
);
CREATE OR REPLACE FUNCTION foobar_table_but()
RETURNS TRIGGER
LANGUAGE plpgsql
AS '
BEGIN
NEW.updated_at := timezone(''utc'', now());
RETURN NEW;
END;
';
CREATE TRIGGER foobar_table_but
BEFORE UPDATE ON foobar
FOR EACH ROW EXECUTE PROCEDURE foobar_table_but();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment