Created
February 21, 2024 12:11
-
-
Save allochi/d81567c397805d32b94a6eb3fa40b78e to your computer and use it in GitHub Desktop.
PostgreSQL add `create_at` and `updated_at` columns
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
ALTER TABLE __table_name__ ADD COLUMN created_at TIMESTAMP; | |
ALTER TABLE __table_name__ ALTER COLUMN created_at SET DEFAULT now(); | |
CREATE OR REPLACE FUNCTION trigger_set_updated_at() | |
RETURNS TRIGGER AS $$ | |
BEGIN | |
NEW.updated_at=now(); | |
RETURN NEW; | |
END; | |
$$ LANGUAGE plpgsql; | |
ALTER TABLE __table_name__ ADD COLUMN updated_at TIMESTAMP; | |
ALTER TABLE __table_name__ ALTER COLUMN updated_at SET DEFAULT now(); | |
-- DROP TRIGGER set_timestam ON testing; | |
CREATE TRIGGER trigger_set_updated_at | |
BEFORE UPDATE ON __table_name__ | |
FOR EACH ROW | |
EXECUTE PROCEDURE trigger_set_updated_at(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment