PostgreSQL ALTER TRIGGER Statement
Summary: in this tutorial, you will learn how to use the PostgreSQL ALTER TRIGGER
statement to rename a trigger.
Introduction to PostgreSQL ALTER TRIGGER statement
The ALTER TRIGGER
statement allows you to rename a trigger. The following shows the syntax of the ALTER TRIGGER
statement:
In this syntax:
- First, specify the name of the trigger you want to rename after the
ALTER TRIGGER
keywords. - Second, provide the name of the table associated with the trigger after the
ON
keyword. - Third, specify the new name of the trigger after the
RENAME TO
keyword.
To execute the ALTER TRIGGER
statement, you must be the owner of the table to which the trigger belongs.
PostgreSQL ALTER TRIGGER example
First, create a new table called employees
:
Second, create a function that raises an exception if the new salary is greater than the old one 100%:
Third, create a before-update trigger that executes the check_salary()
function before updating the salary:
Fourth, insert a new row into the employees
table:
Fifth, update the salary of the employee id 1:
The trigger was fired and issued the following error:
It works as expected.
Finally, use the ALTER TRIGGER
statement to rename the before_update_salary
trigger to salary_before_update
:
If you use psql tool, you can view all triggers associated with a table using the \dS
command:
Notice that the letter S
is uppercase.
Replacing triggers
PostgreSQL doesn’t support the OR REPLACE
statement that allows you to modify the trigger definition like the function that will be executed when the trigger is fired.
To do so, you can use the DROP TRIGGER
and CREATE TRIGGER
statements. You can also wrap these statements within a transaction.
The following example illustrates how to change the check_salary
function of the salary_before_update
trigger to validate_salary
:
Summary
- Use the
ALTER TRIGGER
statement to rename a trigger. - Use the pair of the
DROP TRIGGER
andCREATE TRIGGER
statements to replace a trigger with a new one.