PostgreSQL AFTER DELETE Trigger
Summary: in this tutorial, you will learn how to define a PostgreSQL AFTER DELETE
trigger that is fired after a row is deleted from a table.
Introduction to the PostgreSQL AFTER DELETE trigger
In PostgreSQL, a trigger is a database object that is automatically activated in response to an event including INSERT
, UPDATE
, DELETE
, or TRUNCATE
occurring on a table.
An AFTER DELETE
trigger is activated after one or more rows are deleted from a table.
An AFTER DELETE
trigger can be particularly useful in some scenarios such as logging deleted data, updating data in related tables, or enforcing complex business rules.
In an AFTER DELETE
trigger, the OLD
variable, which holds the value of the row being deleted, is available. To access a column value of the deleted row, you can use the syntax OLD.column_name
.
Notice that you cannot change the column values (OLD.column_name
) because they are read-only.
To create an AFTER DELETE
trigger, you follow these steps:
First, define a trigger function that will execute after a DELETE
operation:
Second, create a trigger and associate the trigger function with it:
PostgreSQL AFTER DELETE trigger example
We’ll use an AFTER DELETE
trigger to archive a deleted row in a separate table.
First, create a table called employees
to store the employee data:
Second, insert two rows into the employees
table:
Output:
Third, create another table named employee_archives
for archiving deleted employees:
Fourth, define a function that inserts a deleted employee into the employee_archives
table:
Fifth, create an AFTER DELETE
trigger that executes the archive_deleted_employee()
function when a row is deleted from the employees
table:
Sixth, delete a row from the employees
table:
Output:
The AFTER INSERT
trigger will be activated that calls the archive_deleted_employee()
function to insert the deleted row into the employee_archives
table.
Seventh, retrieve data from the employee_archives
table:
Output:
The output indicates that the AFTER DELETE
trigger has successfully archived the deleted row into the employee_archives
table.
Summary
- Use a
BEFORE DELETE
trigger to automatically call a function before a row is deleted from a table.