Triggers
About
A trigger is an action or event that causes another event to occur. So a triggering SQL statement causes another SQL statement (the trigger statement) to be executed.
A PostgreSQL trigger is a function invoked automatically whenever 'an event' associated with a table occurs - like (Insert, Update, Delete or Truncate)
A trigger can be associated with a specific Table, View or Foreign Table.
Triggers can trigger:
BEFORE: If the trigger is invoked before an event, it can skip the operation for the current row or even change the row being updated or inserted.AFTER: All changes are available to the trigger.INSTEAD: Of the events/operation.
When multiple triggers are set in a table the order of execution is:
BEFOREtriggers, in alphabetical order.AFTERtrigger, also in alphabetical order.
You can call Stored Procedures and Functions inside triggers.
Avoid:
Too many nested triggers can make it very hard to debug and troubleshoot.
Aggregating/summarizing over the table that you are updating.
Reading data from a table that is updating during the same transaction.
Types of triggers
Row level triggers
If the trigger is marked for each row, then the trigger function will be called for each row that is getting modified by the event.
Statement level triggers
The FOR EACH STATEMENT option will call the trigger function only once for each statement, regardless of the number of the rows getting modified.
Limitations
BEFORE
INSERT / UPDATE / DELETE
Tables
Tables and Views
TRUNCATE
❌
Tables
AFTER
INSERT / UPDATE / DELETE
Tables
Tables and Views
TRUNCATE
❌
Tables
INSTEAD OF
INSERT / UPDATE / DELETE
Views
❌
TRUNCATE
❌
❌
Creating
First, create a trigger function.
Then, bind the trigger function to a table.
Trigger function
Bind the trigger function
Deleting
Special variables
Triggers have special OLD and NEW variables to access values, which:
OLDrepresents the values before the event.NEWrepresents the values after.
Depending on the event they can be NULL.
Usage
Using triggers for auditing
Last updated