PostgreSQL AFTER INSERT Trigger
Summary: in this tutorial, you will learn how to create a PostgreSQL AFTER INSERT
trigger to call a function automatically after a row is inserted into a table.
Introduction to the PostgreSQL AFTER INSERT trigger
In PostgreSQL, a trigger is a database object associated with a table, which is automatically fired in response to an INSERT
, UPDATE
, DELETE
, or TRUNCATE
event.
An AFTER INSERT
trigger is a trigger that is fired after an INSERT
event occurs on a table.
The AFTER INSERT
trigger can access the newly inserted data using the NEW
record variable. This NEW
variable allows you to access the values of columns in the inserted row:
Typically, you use AFTER INSERT
triggers for logging changes, updating related tables, or sending notifications based on the inserted data.
To create an AFTER
INSERT
trigger, you follow these steps:
First, define a function that will execute when the trigger is activated:
The RETURN NEW
statement indicates that the function returns the modified row, which is the NEW
row.
Second, create an AFTER
INSERT
trigger and bind the function to it:
PostgreSQL AFTER INSERT trigger example
First, create a new table called members
to store the member data:
The members
table has three columns id
, name
, and email
. The id
column is a serial and primary key column. The email
column has a unique constraint to ensure the uniqueness of emails.
Second, create another table called memberships
to store the memberships of the members:
The memberships table has three columns id, member_id, and membership_type:
- The
id
is a serial and primary key column. - The
member_id
references the id column of themembers
table. It is a foreign key column. - The
membership_type
column has a default value of “free”.
Third, define a trigger function that inserts a default free membership for every member:
Fourth, define an AFTER
INSERT
trigger on the members
table, specifying that it should execute the create_membership_after_insert()
function for each row inserted:
Fifth, insert a new row into the members
table:
Output:
Sixth, retrieve data from the memberships
table:
Output:
Summary
- Use an
AFTER
INSERT
trigger to call a function automatically after anINSERT
operation successfully on the associated table.