Skip to content

Instantly share code, notes, and snippets.

@carl0smat3us
Last active June 14, 2025 13:01
Show Gist options
  • Select an option

  • Save carl0smat3us/f9ec4c2d6628c8ab83ebcb4c5542457e to your computer and use it in GitHub Desktop.

Select an option

Save carl0smat3us/f9ec4c2d6628c8ab83ebcb4c5542457e to your computer and use it in GitHub Desktop.
Create a trigger to update the updated_at field for every table that has it.
SET TIME ZONE 'America/New_York';
create extension if not exists moddatetime schema extensions;
DO $$
DECLARE
r RECORD;
trigger_name text;
BEGIN
FOR r IN
SELECT table_schema, table_name
FROM information_schema.columns
WHERE column_name = 'updated_at'
AND table_schema = 'public'
LOOP
trigger_name := format('handle_updated_at_%s', lower(r.table_name));
BEGIN
EXECUTE format('
CREATE TRIGGER %I
BEFORE UPDATE ON %I.%I
FOR EACH ROW
EXECUTE FUNCTION moddatetime(''updated_at'')',
trigger_name, r.table_schema, r.table_name);
EXCEPTION
WHEN duplicate_object THEN
END;
END LOOP;
END;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment