Writing triggers in PL/pgSQL

Server-side code is especially popular if you want to react to certain events happening in the database. A trigger allows you to call a function if an INSERT, UPDATE, DELETE, or 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 necessary operation.

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

test=# \h CREATE TRIGGERCommand: CREATE TRIGGERDescription: Define a new triggerSyntax:CREATE [ CONSTRAINT ] TRIGGER name { BEFORE | AFTER | INSTEAD OF }{ event [ OR ... ] }ON table_name[ FROM referenced_table_name ][ NOT DEFERRABLE | [ DEFERRABLE ] [ INITIALLY IMMEDIATE | ...

Get Mastering PostgreSQL 10 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.