Created
January 31, 2025 16:16
-
-
Save cmackenzie1/de557600217682b12142425838ddeb03 to your computer and use it in GitHub Desktop.
PostgreSQL Updated at column trigger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Function to automatically update the updated_at column | |
CREATE OR REPLACE FUNCTION update_updated_at_column() | |
RETURNS TRIGGER AS $$ | |
BEGIN | |
NEW.updated_at = NOW(); | |
RETURN NEW; | |
END; | |
$$ LANGUAGE plpgsql; | |
-- Apply the trigger to all tables with an updated_at column | |
CREATE OR REPLACE FUNCTION create_updated_at_trigger(table_name text) | |
RETURNS void AS $$ | |
BEGIN | |
EXECUTE format(' | |
CREATE TRIGGER update_updated_at_trigger | |
BEFORE UPDATE ON %I | |
FOR EACH ROW | |
EXECUTE FUNCTION update_updated_at_column(); | |
', table_name); | |
END; | |
$$ LANGUAGE plpgsql; | |
-- Create triggers for existing tables | |
SELECT create_updated_at_trigger('users'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Or to run it over all tables in your schema (assuming they have an
updated_at
column)