Database Reference
In-Depth Information
Understanding triggers
A trigger, in terms of databases, means a certain operation to be performed
spontaneously for a speciic database event. For example, this event can be INSERT ,
UPDATE , or DELETE . So, by deining a trigger, you are deining certain operation(s)
to be performed whenever that event occurs. An operation that a trigger refers to is
called a trigger function.
Deining a trigger and deining a trigger function are two different things. The irst
can be created using CREATE TRIGGER and the latter can be created using the CREATE
FUNCTION command. If the irst one says what task to perform, the latter says how to
perform this task.
You have to deine a trigger function irst before creating a trigger.
The following example is an abstract-level code to show how a trigger function
and a trigger are written. You can write a trigger function in PL/pgSQL or any
PostgreSQL-compatible language, for example, PL/Python and PL/Perl. This
example uses PL/pgSQL:
CREATE OR REPLACE FUNCTION trigger_function_name
RETURNS trigger AS $SAMPLE_CODE$
BEGIN
/* your code goes here*/
RETURN NEW;
END;
$SAMPLE_CODE$ LANGUAGE plpgsql;
You can refer to the online PostgreSQL manual at http://www.
postgresql.org/docs/9.4/static/index.html for a
detailed reference on general syntax and in-depth explanation of the
implementation of trigger, rules, and views.
The simple form of the CREATE TRIGGER syntax is as follows:
CREATE TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF} {event
[OR ...]}
ON table_name
[FOR [EACH] {ROW | STATEMENT}]
EXECUTE PROCEDURE trigger_function_name
So, a trigger function is a function but with the difference that it does not take
arguments such as ordinary functions but through a special data structure called
TriggerData ; its return type is trigger , and it is automatically invoked when an
event occurs that can be INSERT , UPDATE , DELETE , or TRUNCATE .
 
Search WWH ::




Custom Search