PostgreSQL AFTER UPDATE Trigger
Summary: in this tutorial, you will learn how to define a PostgreSQL AFTER UPDATE
trigger that executes a function after an update event occurs.
Introduction to the PostgreSQL AFTER UPDATE trigger
In PostgreSQL, a trigger is a database object that is fired automatically when an event such as INSERT
, UPDATE
, DELETE
, or TRUNCATE
occurs.
An AFTER UPDATE
trigger is a type of trigger that fires after an UPDATE
operation is completed successfully on a table.
Because the AFTER UPDATE
triggers can access the row after the update, you can perform tasks such as logging changes, updating data in related tables, or sending notifications based on the modified data.
In an AFTER UPDATE
trigger, you can access the following variables:
OLD
: This record variable allows you to access the row before the update.NEW
: This record variable represents the row after the update.
Additionally, you can access the following variables:
TG_NAME
: Store the name of the trigger.TG_OP
: Represent the operation that activates the trigger, which isUPDATE
for theAFTER
UPDATE
trigger.TG_WHEN
: Represent the trigger timing, which isAFTER
for theAFTER UPDATE
trigger.
To create a AFTER UPDATE
trigger, you use the following steps:
First, define a trigger function that will execute when the AFTER UPDATE
trigger fires:
Second, create a AFTER UPDATE
trigger that executes the trigger function:
PostgreSQL AFTER UPDATE trigger example
First, create a new table called salaries
to store the employee’s salaries:
Second, create a table called salary_changes
that stores the updates to the salary
column of the salaries
table:
Third, define the function log_salary_changes()
that logs the changes of values in the salary
column to the salary_changes
table:
Fourth, define an AFTER UPDATE
trigger that calls the log_salary_change()
function after an update occurs to the salary
column of the salaries
table:
Fifth, insert some rows into the salaries
table:
Output:
Sixth, increase the salary of John Doe
by 5%:
Seventh, retrieve the data from salary_changes
table:
Output:
The output shows that the salary before and after changes have been logged to the salary_changes
table.
Summary
- Use a
BEFORE
UPDATE
trigger to execute a function before an update operation occurs.