Introduction to PostgreSQL Triggers
PostgreSQL trigger will be associated with a specific view or table; it will execute with a specified function when a certain event occurs. PostgreSQL trigger is used to execute the specified events at a specific time using events. PostgreSQL trigger will invoke automatically when any event (Insert, Update or delete) occurs on a table or views. To create a new trigger in PostgreSQL, we need to define the trigger function first, and then we have binding this trigger function to the specified table.
The main difference between PostgreSQL trigger and user-defined function is trigger was automatically invoked when a specified event occurs.
Syntax and Parameters of PostgreSQL trigger
Create a trigger statement is used to create a new trigger in PostgreSQL. The trigger will occur when any particular or specific event occurs on a table or view.
Syntax
CREATE [ CONSTRAINT ] TRIGGER name(must be distinct of any other trigger in same table) { BEFORE | AFTER | INSTEAD OF } { event (Event Name)[ OR ... ] }
ON table (Table_name)
[FROM referenced_table_name]
[NOT DEFERRABLE | [DEFERRABLE] {INITIALLY IMMEDIATE | INITIALLY DEFERRED} ]
[FOR [EACH] {ROW | STATEMENT} ]
[WHEN (condition) ]
EXECUTE PROCEDURE function name (arguments)
Where event can be one of the following:
INSERT
UPDATE [OF Column_name [, ... ] ]
DELETE
TRUNCATE
Parameter
- Name – The name of the trigger. This name will be distinct from any other trigger from the same table.
- Before – Determines that we are calling the function before the event.
- After – Determines that we are calling the function after the event.
- Instead Of – Determines that we are calling the function instead of the event.
- Event – Any of the event like Insert, Update, delete or truncate will fire the trigger.
- Table name – Name of the table or view
- Referenced table name – This is the name of other tables which is referenced by constraints. This option only specified with constraints triggers.
- DEFERRABLE, NOT DEFERRABLE, INITIALLY IMMEDIATE and INITIALLY DEFERRED – This is the PostgreSQL trigger’s default time.
- For each row, this will specify that the trigger will be fired once for every row affected by trigger events.
- For each statement – If we have not specified any row or statement, this will default. This will specify that it will be fired once for every statement affected by a trigger event.
- Condition – Condition will be the Boolean expression that determines that trigger function will be executed.
- Function name – User-supplied function that is not arguments, and it will return trigger.
- Arguments – This is an optional comma-separated argument provided to the function, then the trigger was executing.
PostgreSQL Triggers Working
Below is the working of PostgreSQL Triggers.
- It is a set of actions that run automatically when specific database event like (Insert, Update, Delete and Truncate) will perform on a table.
- It will provide two important types of triggers.
- Row-level triggers
- Statement level triggers
- If the trigger is marked as FOR EACH ROW, then it will be called once for every row that the operation was modified.
- If the trigger is marked as FOR EACH STATEMENT, then it will be called once for every statement that the operation was modified.
- The main difference between the row-level trigger and statement-level triggers is that if we are updating 20 rows in a single table, row-level triggers will be invoked 20 times. Instead of that, statement-level triggers are executed only one time.
- By default, statement-level triggers were invoked if we don’t define the level of triggers.
- We can also specify whether the trigger is invoked before or after an event occurs. If the trigger was invoked after the event, all changes are available to the trigger. In case it was invoked before, it will skip operation from the current row.
- It is essential and useful when a single database accessed by much application.
- It is also useful when we are maintaining complex data integrity rules that rule we cannot implement elsewhere except database level.
- Creating a new trigger in PostgreSQL first, we need to create a trigger function. It does not take any argument; it will return value with the type of trigger.
- Following is the syntax of creating a trigger function are as follows.
Creat Trigger Function
Below is the syntax for creating Trigger Function:
Syntax:
CREATE FUNCTION trigger_function_name ()
RETURNS trigger AS
- We can create a trigger function in any language that PostgreSQL supported. It will receive data from its calling environment through a special structure called trigger data.
- Trigger data contains a set of local variables in the PostgreSQL trigger function.
- After creating a trigger function, we can bind it into one or more trigger events such as Update, Truncate, Delete and Insert.
The function is defined in the following compatible languages:
- PL/pgsql
- PL/Python
- Pl/ Java
Examples of PostgreSQL Triggers
Please find below the steps to create the trigger in PostgreSQL.
Example #1 – Create a table and insert a record for testing
Code:
testing=# CREATE TABLE employee ( emp_name character(100) NOT NULL, emp_email character(20) NOT NULL, emp_phone character(14));
testing=# CREATE TABLE employee_history ( log_id character(100) NOT NULL);
testing=# INSERT INTO EMPLOYEE (emp_name, emp_email, emp_phone) VALUES ('ABC', 'abc@gmail.com', '1234567890');
testing=# INSERT INTO EMPLOYEE (emp_name, emp_email, emp_phone) VALUES ('PQR', 'pqr@gmail.com', '1234567890');
testing=# INSERT INTO EMPLOYEE (emp_name, emp_email, emp_phone) VALUES ('XYZ', 'xyz@gmail.com', '1234567890');
Output:
Example #2 – Create a trigger function
We have created a trigger function name as trigger_testing.
Code:
CREATE OR REPLACE FUNCTION trigger_testing()
RETURNS trigger
AS $test_trigger$
BEGIN
INSERT INTO employee_history (log_id) VALUES (new.id);
RETURN NEW;
END;
$test_trigger$
LANGUAGE plpgsql;
Output:
Example #3 – Create a trigger
We have to create a trigger name as a trigger_test.
Code:
CREATE TRIGGER trigger_test
AFTER INSERT ON employee
FOR EACH ROW
EXECUTE PROCEDURE trigger_testing();
Output:
Example #4 – Drop trigger in PostgreSQL
To drop trigger in PostgreSQL drop trigger statement is used.
Syntax
DROP TRIGGER trigger_name on table_name;
Example
testing=# drop trigger trigger_test on the employee;
Output:
Conclusion
For creating a new trigger in PostgreSQL CREATE TRIGGER statement is used. Row-level and statement-level triggers are two main important types of PostgreSQL triggers.
It always refers to a function that was triggered automatically when the event occurs on database tables or views.
Recommended Articles
This is a guide to PostgreSQL Triggers. Here we discuss the basic concept, examples of PostgreSQL Triggers, along with the steps and syntax. You may also have a look at the following articles to learn more –