Creating the trigger function
The trigger function 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 the trigger is in the before and after states of the triggering event. Additionally, there are several other local variables starting 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 for creating a user-defined TRIGGER
statement is given as follows:
CREATE TRIGGER name { BEFORE | AFTER | INSTEAD OF } { event [ OR ... ] } ON table_name ...