91-9990449935 0120-4256464 |
PostgreSQL TriggersPostgreSQL Triggers are a set of actions or database callback functions that run automatically when a specified database event (i.e. INSERT, UPDATE, DELETE or TRUNCATE statement) is performed on a specified table. Triggers are used to validate input data, enforce business rules, keeping audit trail etc. Important points about Triggers
Before the operation is attempted (before constraints are checked and the INSERT, UPDATE or DELETE is attempted). Or, after the operation has completed (after constraints are checked and the INSERT, UPDATE, or DELETE has completed). Or, Instead of the operation (in the case of inserts, updates or deletes on a view) PostgreSQL Create TriggerThe CREATE TRIGGER statement is used to create a new trigger in a PostgreSQL table. It is activated when a particular event (i.e. INSERT, UPDATE, and DELETE) occurs for the table. Syntax: Here, event_name could be INSERT, UPDATE, DELETE, and TRUNCATE database operation on the mentioned table table_name. You can optionally specify FOR EACH ROW after table name. Let's see the syntax of creating a trigger on an INSERT operation. Let's take an example to demonstrate PostgreSQL create trigger AFTER INSERT statement. See this example: In the following example, we keep audit trial for every record being inserted in COMPANY table. Create a table named COMPANY, by using the following query: To keep audit trial, we will create a new table called AUDIT where log messages will be inserted whenever there is an entry in COMPANY table for a new record. Create another table Audit, by using the following query: Before creating a trigger on company table, first create a function/ procedure named auditlogfunc(). Execute the following query: Now create a trigger on COMPANY table by using the following query: Execute the following query: Insert some values in the COMPANY table. At the same time, two records will be created in AUDIT table. These records are the result of trigger, which we have created on AFTER INSERT on COMPANY table. Usage of PostgreSQL TriggersPostgreSQL triggers can be used for following purposes:
Advantages of using triggers
Next TopicPostgreSQL Alias
|