PostgreSQL BEFORE INSERT Trigger
Summary: in this tutorial, you will learn how to create a PostgreSQL BEFORE INSERT
trigger associated with a table.
Introduction to PostgreSQL BEFORE INSERT trigger
A trigger is a database object that automatically calls a function when an event such as INSERT
, UPDATE
, and DELETE
statement occurs on the associated table.
A BEFORE INSERT
trigger is activated before an INSERT
event occurs on a table. To create a BEFORE INSERT
trigger, you follow these steps:
First, define a trigger function that will execute before the INSERT
event occurs:
At the end of the function, you need to place the RETURN NEW
statement
Second, create a BEFORE INSERT
trigger and associate a trigger function with it:
PostgreSQL BEFORE INSERT trigger example
First, create a table called inventory
to store inventory data:
Second, create a table called inventory_stat
that stores the total quantity of all products:
Third, define a function that increases the total quantity in the inventory_stat
before a row is inserted into the inventory
table:
If the inventory_stat table has no rows, the function inserts a new row with the quantity being inserted into the inventory table. Otherwise, it updates the existing quantity.
Fourth, define a BEFORE INSERT
trigger associated with the inventory
table:
Fifth, insert a row into the inventory table:
Output:
Sixth, retrieve data from the inventory_stat
table:
Output:
Seventh, insert another row into the inventory
table:
Output:
Eighth, retrieve the data from the inventory_stat
table:
Summary
- A
BEFORE INSERT
trigger is activated before anINSERT
event occurs on a table.