I have a simple function triggered on any updates to a PostgreSQL 14 table:
CREATE OR REPLACE FUNCTION track_changes() RETURNS TRIGGER AS $body$
BEGIN
raise notice 'old is: "%"', OLD;
raise notice 'new is: "%"', NEW;
END;
$body$
LANGUAGE plpgsql
;
CREATE TRIGGER update_trigger
AFTER UPDATE ON students
FOR EACH ROW EXECUTE PROCEDURE track_changes();
However, the function is meant to be used with many different tables – i.e. I don’t know which columns are available. How can I, within the trigger function, calculate the set of columns which differ between OLD
and NEW
– e.g. as a record
or row
or even JSONB
value?
2
Answers
You’ll have to query the metadata:
Here is a JSONB-based suggestion. Convert
new
andold
to JSONB so that you could extract the keys (these are the table column names) and iterate over them.