Triggers
A postgresql trigger is a functoin invoked automatically whenever 'an event' associated with a table occurs.
An event could be any of the following;
INSERT
UDPATE
DELETE
TRUNCATE
You can associate a trigger with a
Table
View
Foreign Table
A trigger is a special 'user-defined function'
A trigger is automatically invoked
We can create a triger
BEFORE
Trigger is fired before an event is about to happen
AFTER
Trigger is fired after the event is completed
INSTEAD
In case the event fails, trigger is fired
Cannot be fired manually
Fired in alphbetically order
DO Not change in primary key, foriegn key or unique key column
DO Not update records in the table that you normally read during the transaction
DO Not read data from a table that is updating during the same transaction
DO Not aggregate/summarized over the table that you are updating
Types of Triggers
Row level
If row is marked for
FOR EACH ROW
, then trigger will be called for each row that is getting modfied by the event
Statement level
The
FOR EACH STATEMENT
will call the trigger function only ONCE for each statement, regardless of the number of rows getting modified.
INSERT/UDPATE/DELETE
Tables
Tables and view
before
Truncate
----------
--------------------
---------
---------------
INSERT/UDPATE/DELETE
Tables
Tables and view
AFTER
Truncate
----------
--------------------
---------
---------------
INSERT/UDPATE/DELETE
Views
INSTEAD OF
Truncate
Create your own Trigger in PostgreSQL
Syntax
Data Auditing with Triggers
Setup Example tables
Setup Function to TRIGGER
DML to fire above trigger
Another Trigger Example
Last updated