Writing triggers in PL/pgSQL

Server-side code is especially popular if you want to react on certain events happening in the database. A trigger allows you to call a function if an INSERT, UPDATE, DELETE or a TRUNCATE clause happens on a table. The function called by the trigger can then modify the data changed in your table or simply perform some operation needed.

In PostgreSQL, triggers have become ever more powerful over the years and provide a rich set of features:

test=# h CREATE TRIGGER Command:     CREATE TRIGGER Description: define a new trigger Syntax: CREATE [ CONSTRAINT ] TRIGGER name { BEFORE | AFTER | INSTEAD OF }              { event [ OR ... ] }     ON table_name     [ FROM referenced_table_name ]     [ NOT DEFERRABLE | [ DEFERRABLE ]   [ INITIALLY ...

Get Mastering PostgreSQL 9.6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.