postgresql_16:7.1.91.4 Examples
PostgreSQL 16 > Reference > SQL Commands > CREATE TRIGGER > Examples
Execute the function check_account_update whenever a row of the table accounts is about to be updated: CREATE TRIGGER check_update BEFORE UPDATE ON accounts FOR EACH ROW EXECUTE FUNCTION check_account_update(); Modify that trigger definition to only execute the function if column balance is specified as a target in the UPDATE command: CREATE OR REPLACE TRIGGER check_update BEFORE UPDATE OF balance ON accounts FOR EACH ROW EXECUTE FUNCTION check_account_update(); This form only executes the function if column balance has in fact changed value: CREATE TRIGGER check_update BEFORE UPDATE ON accounts FOR EACH ROW WHEN (OLD.balance IS DISTINCT FROM NEW.balance) EXECUTE FUNCTION check_account_update(); Call a function to log updates of accounts, but only if something changed: CREATE TRIGGER log_update AFTER UPDATE ON accounts FOR EACH ROW WHEN (OLD.* IS DISTINCT FROM NEW.*) EXECUTE FUNCTION log_account_update(); Execute the function view_insert_row for each row to insert rows into the tables underlying a view: CREATE TRIGGER view_insert INSTEAD OF INSERT ON my_view FOR EACH ROW EXECUTE FUNCTION view_insert_row(); Execute the function check_transfer_balances_to_zero for each statement to confirm that the transfer rows offset to a net of zero: CREATE TRIGGER transfer_insert AFTER INSERT ON transfer REFERENCING NEW TABLE AS inserted FOR EACH STATEMENT EXECUTE FUNCTION check_transfer_balances_to_zero(); Execute the function check_matching_pairs for each row to confirm that changes are made to matching pairs at the same time (by the same statement): CREATE TRIGGER paired_items_update AFTER UPDATE ON paired_items REFERENCING NEW TABLE AS newtab OLD TABLE AS oldtab FOR EACH ROW EXECUTE FUNCTION check_matching_pairs();
(see postgresql_16:6.2.4) contains a complete example of a trigger function written in C.