
Triggers in PostgreSQL allow developers to define rules and actions which can be executed without their manual intervention, making database management more efficient. By utilizing triggers in a database, users can create a dynamic and responsive database that responds and adapt to the changes made in the application.
This article walks you through the functionality of triggers in PostgreSQL. It demonstrates the steps to create, alter and drop a trigger function.
psql CLI tool on your computer to connect to the database.Trigger functions are called when specific actions such as data modification operations like INSERT, DROP, and ALTER, are called. This allows developers to perform event-driven queries within the database.
The following are the components for creating triggers.
Below are some user cases for implementing triggers.
Data Definition Langauge (DDL) Triggers
DDL consists of commands such as CREATE, DROP, and ALTER. When DDL commands are called within the trigger function, it's called a DDL Trigger.
Data Manipulation Langauge (DML) Triggers
DML consists of commands such as INSERT, UPDATE, and DELETE. When DML commands are called within the trigger function, it's called a DML Trigger.
LOGON Triggers
This consists of the LOGON command which is fired before a user session is established. Therefore all the messages defined by the developer, such as error and success messages are redirected to a SQL server as a SQL Server log.
In this section, set up a new database with a users table, and users_log to log changes using a trigger in PostgreSQL as described below.
Log in to your Vultr Managed Database for PostgreSQL.
Replace mydb.postgres.vultr.com, 5432, admin with your account Vultr Managed Database details.
Create a new database named DB1.
Switch to the database.
Create a new users table.
The users table consists of 3 columns, user_id, user_name, and their address. Operations such as insert and update will only run in the users table, and the users_log table consists of similar columns with similar column constraints.
Create the users_log table.
Verify that the tables are created.
Output:
Populate data to the users table.
View the table data.
Output:
Verify that the users_log table has no stored data.
Output:
You have created 2 tables named users and users_log. You will implement a trigger function to log any changes made in the users table to the users_log table.
In this section create a trigger function using the inbuilt CREATE SQL operation followed by the keyword FUNCTION as described below.
Create a trigger function.
Below is what the above SQL command does:
The function name users_log_trg_func is suffixed with (). There are multiple functions in PostgreSQL and it's necessary to label the function as a trigger and RETURNS TRIGGER is used for this purpose. plpgsql represents the assigned procedural language supported by the PostgreSQL Object Relational Database Management System (ORDBMS).
$$ acts as a delimiter used when writing a multi-line string literal. Using $$ specifies that anything written after this should be treated as a single string literal. The BEGIN operator marks the beginning of the function's main executable block.
The above code implements a trigger that uses old data (before performing an update or delete) in the users table, and inserts it in the users_log table, the OLD keyword is used to store only old data in the table.
This ensures that the value of the row after the trigger event has occurred. END and $$ ensure that the trigger function's body is concluded without any errors.
To successfully use a trigger function, create a trigger event as described below.
Create a trigger event.
Below is what the above SQL statement does:
The CREATE operation creates a trigger followed by the keyword TRIGGER to create a trigger named users_trig.
Specifies the event condition on which the trigger must be called. The trigger must be called before a delete or update event is called on a table. For this article, the users table.
Defines when it's required for the trigger functions to run for each row.
Links the trigger function to the trigger command.
A trigger event is activated when an UPDATE or DELETE command runs. In the following command, the trigger function is called automatically.
The above command updates the user id 1 in the users table.
View the updated users table data.
Output:
View the users_log table data.
Output:
No changes are made manually to the users_log table. But, as soon as the UPDATE command is executed, the trigger function is called to add old data from the users table to the users_log table. The old username, john, is now stored in the users_log table and the updated name John Doe is only available in the main users table.
Execute another update statement:
The updated users table data should be:
Verify that the users_log table has more data from the trigger function.
Output:
This shows that the trigger function is working and it's able log old data to the users_log table
After creating a trigger function, you can still enable, disable, drop, or alter the function using the following functions.
To disable a trigger function, you can use the ALTER TABLE operation to modify the structure or property of the table. This is followed by the table name, and the DISABLE keyword which stops the trigger from making any further changes using the syntax below.
For example, disable the users table trigger as below.
Similar to disable, you can re-enable the trigger function in case it's disabled using the syntax below.
For example:
To update a trigger, use the REPLACE keyword. Other body commands can remain the same as before using the syntax below.
For example:
To permanently delete a trigger, you can use the DROP command. But to avoid any errors, it's a good practice to use IF EXISTS using the syntax below.
For example:
These are optional commands that are only used when writing multiple condition lines within a trigger function. It's a good practice to use BEGIN and END when writing any new query.
If FOR EACH ROW is not specified, the trigger function is executed once irrespective of how many rows are being updated. Using FOR EACH ROW enables the trigger to run on each predefined row.
The WHERE clause can be used within a trigger function to make sure the trigger is executed only when certain conditions are met. For example:
In the above query, the trigger filters the user address column to return values with Miami, FL.
Raise logs a warning or notice when a trigger function is executed. It's useful for establishing communication while the trigger function is executed.
The above query establishes a warning communication when the user_id is null. If the condition is true, a notice with the text 'User name is missing' is generated. Other variants of the raise function such as RAISE WARNING or RAISE EXCEPTION offer different levels of severity
In this article, you implemented the fundamental concepts of triggers in PostgreSQL. You also created a trigger function, and set up trigger events to perform operations on triggers and other advanced configurations. It's important to note that although triggers offer more flexibility, a poorly configured trigger will cause significant performance loss and unwanted complications. Therefore, proper planning and testing of such functions is required to make sure the triggers align with the database requirements.
For more information, visit the following resources.
0 Comments
Be the first to comment and share your perspective with the community.