Difference between revisions of "PostgreSQL Snippets"
Jump to navigation
Jump to search
Line 1: | Line 1: | ||
# Update update_at when table specified at bottom is updated. | # Update update_at when table specified at bottom is updated. | ||
+ | ``` | ||
+ | CREATE OR REPLACE FUNCTION update_updated_at_column() | ||
+ | RETURNS TRIGGER AS $$ | ||
+ | BEGIN | ||
+ | IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN | ||
+ | NEW.updated_at = now(); | ||
+ | RETURN NEW; | ||
+ | ELSE | ||
+ | RETURN OLD; | ||
+ | END IF; | ||
+ | END; | ||
+ | $$ language 'plpgsql'; | ||
+ | |||
+ | CREATE TRIGGER mytable_update_at_ts | ||
+ | BEFORE UPDATE ON urls FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column(); | ||
+ | ``` | ||
+ | |||
+ | |||
``` | ``` | ||
SELECT 'up SQL query'; | SELECT 'up SQL query'; |
Latest revision as of 00:24, 3 April 2022
Update update_at when table specified at bottom is updated.
CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN NEW.updated_at = now(); RETURN NEW; ELSE RETURN OLD; END IF; END; $$ language 'plpgsql'; CREATE TRIGGER mytable_update_at_ts BEFORE UPDATE ON urls FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column();
SELECT 'up SQL query'; # Update updated_at column on update CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = now(); RETURN NEW; END; $$ language 'plpgsql'; or even better but more costly compute if only if content has changed CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN NEW.updated_at = now(); RETURN NEW; ELSE RETURN OLD; END IF; END; $$ language 'plpgsql'; BEFORE UPDATE ON my_table FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column();