Book Image

PostgreSQL Server Programming - Second Edition

Book Image

PostgreSQL Server Programming - Second Edition

Overview of this book

Table of Contents (21 chapters)
PostgreSQL Server Programming Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Creating the trigger function


The trigger function's definition looks mostly like an ordinary function definition, except that it has a return value type, trigger, and it does not take any arguments:

CREATE FUNCTION mytriggerfunc() RETURNS trigger AS $$ …

Trigger functions are passed information about their calling environment through a special TriggerData structure, which in the case of PL/pgSQL is accessible through a set of local variables. The local variables, OLD and NEW, represent the row in which the trigger is in before and after triggering the event. Additionally, there are several other local variables that start with the prefix TG_, such as TG_WHEN or TG_TABLE_NAME for general context. Once your trigger function is defined, you can bind it to a specific set of actions on a table.

Creating the trigger

The simplified syntax to create a user-defined TRIGGER statement is given as follows:

CREATE TRIGGER name
    { BEFORE | AFTER | INSTEAD OF } { event [ OR ... ] }
    ON table_name
  ...