Creating a PostgreSQL Trigger with a When Condition
Summary: in this tutorial, you will learn how to create a conditional trigger that fires only when a condition is true.
In PostgreSQL, a trigger is a database object that automatically executes a function when INSERT
, UPDATE
, DELETE
, or TRUNCATE
event occurs on a table.
Sometimes, you want the trigger to be activated only when a specific condition is met. To do that, you specify a boolean condition in the WHEN
clause of the CREATE TRIGGER statement, like so:
In this syntax, the condition
is a boolean expression. If the condition
is true, the trigger is fired; otherwise, the trigger will not be activated.
In row-level triggers, you can access the old/new values of columns of the row within the condition. However, in statement-level triggers, you do not have access to column values.
PostgreSQL Trigger When Condition example
First, create a table called orders
to store order data:
Second, create another table called customer_stats
to store the total spent amount by customers:
Third, create an AFTER INSERT trigger that inserts a row into the customer_stats
table when a new row is inserted into the orders
table:
Fourth, define an AFTER UPDATE
trigger on the orders
table with a condition:
The AFTER UPDATE
trigger fires only when the status of the row changes from non-completed state to completed.
Fifth, insert some rows into the orders
table:
The AFTER INSERT
trigger fires and insert rows into the customer_stats
table.
Sixth, change the order statuses of customer id 1 and 2 to completed
:
The AFTER UPDATE
trigger fires and updates the total_spent
column in the customer_stats
table.
Finally, retrieve the data from the customer_stats
table:
Output:
Summary
- Specify a condition in the
WHEN
clause of theCREATE TRIGGER
statement to instruct PostgreSQL to fire the trigger when the condition is true.