PostgreSQL BEFORE DELETE Trigger
Summary: in this tutorial, you will learn how to define a PostgreSQL BEFORE DELETE
trigger that is fired before a row is deleted from a table.
Introduction to the PostgreSQL BEFORE 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.
A BEFORE DELETE
trigger is activated before one or more rows are deleted from a table.
In practice, you’ll use BEFORE DELETE
triggers for tasks such as logging deleted data, updating data in related tables, or enforcing complex business rules.
In a BEFORE DELETE
trigger, you can access the OLD
variable, which holds the value of the row being deleted. To access a column value of the deleted row, you can use the syntax OLD.column_name
.
Please note that you cannot modify the column values (OLD.column_name
) because they are read-only.
To create a BEFORE DELETE
trigger, follow these steps:
First, define a trigger function that will execute before a DELETE
operation:
Second, create a trigger and associate the trigger function with it:
PostgreSQL BEFORE DELETE trigger example
We’ll use a BEFORE DELETE
trigger to prevent applications from deleting a row in a table.
First, create a table called products
that stores the product data:
Next, insert some rows into the products
table:
Output:
Then, create a BEFORE DELETE
trigger function that raises an exception:
After that, create a BEFORE DELETE
trigger on the products
table:
Finally, delete a row from the products
table:
Error:
Summary
- Use a
BEFORE DELETE
trigger to automatically call a function before a row is deleted from a table.