PostgreSQL Trigger
A PostgreSQL trigger is a callback function of the database that is automatically executed/called when a specified database event occurs.
The following are several important points about PostgreSQL triggers:
-
PostgreSQL triggers can be fired in the following situations:
- Before executing an operation (before checking constraints and attempting to insert, update, or delete).
- After executing an operation (after checking constraints and completing the insert, update, or delete).
- Update operation (when inserting, updating, or deleting on a view).
-
The FOR EACH ROW attribute of a trigger is optional; if selected, it is called once per row when the operation modifies rows. In contrast, with FOR EACH STATEMENT, the trigger marked for each statement executes once regardless of how many rows are modified.
-
The WHEN clause and trigger action can access each row's elements when referencing NEW.column-name and OLD.column-name forms during insert, delete, or update. Here column-name is the name of a column in the table associated with the trigger.
-
If a WHEN clause exists, the PostgreSQL statement only executes for the row where the WHEN clause is true; if there is no WHEN clause, the PostgreSQL statement executes for every row.
-
The BEFORE or AFTER keyword determines when the trigger action is executed, i.e., whether the trigger action is executed before or after the insert, modification, or deletion of the associated row.
-
The table to be modified must exist in the same database as the table or view to which the trigger is attached, and only tablename must be used, not database.tablename.
-
Constraint options are specified when creating a constraint trigger. This is the same as a regular trigger, except that such a constraint can be used to adjust the timing of the trigger firing. When the constraint implemented by a constraint trigger is violated, it throws an exception.
Syntax
The basic syntax for creating a trigger is as follows:
CREATE TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] event_name
ON table_name
[
-- Trigger logic....
];
Here, event_name can be the INSERT, DELETE, and UPDATE database operations on the mentioned table table_name. You can optionally specify FOR EACH ROW after the table name.
The following is the syntax for creating a trigger on one or more specified columns of a table for an UPDATE operation:
CREATE TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name
ON table_name
[
-- Trigger logic....
];
Example
Let's assume a situation where we want to keep an audit trail for every record inserted into the newly created COMPANY table (dropped and recreated if it already exists):
runoobdb=# CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
To keep the audit trail, we will create a new table named AUDIT. Whenever a new record entry appears in the COMPANY table, a log message will be inserted into it:
runoobdb=# CREATE TABLE AUDIT(
EMP_ID INT NOT NULL,
ENTRY_DATE TEXT NOT NULL
);
Here, ID is the ID of the AUDIT record, EMP_ID is the ID from the COMPANY table, and DATE will hold the timestamp when the record in COMPANY was created. So, now let's create a trigger on the COMPANY table as follows:
runoobdb=# CREATE TRIGGER example_trigger AFTER INSERT ON COMPANY FOR EACH ROW EXECUTE PROCEDURE auditlogfunc();
auditlogfunc() is a PostgreSQL program, defined as follows:
CREATE OR REPLACE FUNCTION auditlogfunc() RETURNS TRIGGER AS $example_table$
BEGIN
INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, current_timestamp);
RETURN NEW;
END;
$example_table$ LANGUAGE plpgsql;
Now, we start inserting data into the COMPANY table:
runoobdb=# INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 );
At this point, a record has been inserted into the COMPANY table:
At the same time, a record has also been inserted into the AUDIT table because we created a trigger when inserting into the COMPANY table. Similarly, we can also create triggers for updates and deletes as needed:
emp_id | entry_date
--------+-------------------------------
1 | 2013-05-05 15:49:59.968+05:30
(1 row)
List triggers
You can list all triggers in the current database from the pg_trigger table:
runoobdb=# SELECT * FROM pg_trigger;
If you want to list the triggers of a specific table, the syntax is as follows:
runoobdb=# SELECT tgname FROM pg_trigger, pg_class WHERE tgrelid=pg_class.oid AND relname='company';
The result is as follows:
tgname
-----------------
example_trigger
(1 row)
Drop a trigger
The basic syntax for dropping a trigger is as follows:
drop trigger ${trigger_name} on ${table_of_trigger_dependent};
The command to drop the trigger example_trigger on the company table in this article is:
drop trigger example_trigger on company;