PostgreSQL BEFORE UPDATE Trigger
Summary: in this tutorial, you will learn how to define a PostgreSQL BEFORE UPDATE
trigger that executes a function before an update event occurs.
Introduction to the PostgreSQL BEFORE UPDATE trigger
In PostgreSQL, a trigger is a database object that is automatically activated when an event such as INSERT
, UPDATE
, DELETE
, or TRUNCATE
occurs on the associated table.
A BEFORE UPDATE
trigger is a type of trigger that activates before an UPDATE
operation is applied to a table.
These BEFORE UPDATE
triggers can be particularly useful when you want to modify data before an update occurs or enforce certain conditions.
In a BEFORE 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.
Also, you can access the following variables:
TG_NAME
: Represent the name of the trigger.TG_OP
: Represent the operation that activates the trigger, which isUPDATE
for theBEFORE UPDATE
triggers.TG_WHEN
: Represent the trigger timing, which isBEFORE
for theBEFORE UPDATE
triggers.
To create a BEFORE UPDATE
trigger, you follow these steps:
First, define a trigger function that will execute when the BEFORE UPDATE
trigger fires:
Second, create a BEFORE UPDATE
trigger that executes the defined function:
PostgreSQL BEFORE UPDATE trigger example
First, create a new table called employees
to store the employee data:
Next, define a trigger function that raises an exception if the new salary is lower than the current salary. The trigger will prevent the update when the exception occurs.
Then, create a BEFORE UPDATE
trigger that executes the fn_before_update_salary()
before the update:
This BEFORE UPDATE
trigger ensures that the salary of the employee cannot be decreased. If you attempt to reduce the salary, the trigger will raise an exception and abort the update.
After that, insert some rows into the employees
table:
Output:
Finally, attempt to decrease the salary of John Doe
:
The BEFORE UPDATE
trigger raises the following exception:
Summary
- Use a
BEFORE UPDATE
trigger to automatically execute a function before an update.