Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sgoley/5fdadc20ae32e191bf1f8db172d002dd to your computer and use it in GitHub Desktop.
Save sgoley/5fdadc20ae32e191bf1f8db172d002dd to your computer and use it in GitHub Desktop.
easiest way to manage both "created" and "updated" timestamps on a record in postgesql
-- in schema as procedure:
create function manage_magic_timestamp_columns() returns trigger
strict
cost 1
language plpgsql
as
$$
BEGIN
-- is a new record?
IF TG_OP = 'INSERT' THEN
-- yes, set created at
NEW.created_at = current_timestamp;
END IF;
-- bump updated at column
NEW.updated_at = current_timestamp;
-- all done
RETURN NEW;
END;
$$;
comment on function manage_magic_timestamp_columns() is 'Manage magic timestamp columns';
alter function manage_magic_timestamp_columns() owner to --your username here--;
-- on table:
-- Trigger: table_magic_ts_tr
-- DROP TRIGGER table_magic_ts_tr ON public.table;
CREATE TRIGGER table_magic_ts_tr
BEFORE INSERT OR UPDATE
ON public.table
FOR EACH ROW
EXECUTE PROCEDURE public.manage_magic_timestamp_columns();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment