![]() |
VOOZH | about |
In PostgreSQL, triggers are a powerful mechanism to automate tasks and enforce business rules. Sometimes, you may need to modify a trigger, such as renaming it, to reflect changes in your application or database design.
PostgreSQLprovides the ALTERTRIGGER statement for this purpose, an extension of the SQL standard.
ALTER TRIGGER trigger_name ON table_name
RENAME TO new_name;
Let's analyze the above syntax:
Let us take a look at an example of ALTER TRIGGER Examples in PostgreSQL to better understand the concept.
First, we create a staff table for demonstration with the below statement:
CREATE TABLE staff( user_id serial PRIMARY KEY, username VARCHAR (50) UNIQUE NOT NULL, password VARCHAR (50) NOT NULL, email VARCHAR (355) UNIQUE NOT NULL, created_on TIMESTAMP NOT NULL, last_login TIMESTAMP );
Create a function that validates the username of a staff. The username of staff must not be null and its length must be at least 8.
CREATE FUNCTION check_staff_user() RETURNS TRIGGERAS $$ BEGIN IF length(NEW.username) < 8 OR NEW.username IS NULL THEN RAISE EXCEPTION 'The username cannot be less than 8 characters'; END IF; IF NEW.NAME IS NULL THEN RAISE EXCEPTION 'Username cannot be NULL'; END IF; RETURN NEW;END; $$ LANGUAGE plpgsql;
Create a new trigger on the staff table to check the username of a staff. This trigger will fire whenever you insert or update a row in the staff table.
CREATE TRIGGER username_check BEFORE INSERT OR UPDATEON staff FOR EACH ROW EXECUTE PROCEDURE check_staff_user();
Now to modify the above-created trigger use the below statement:
ALTER TRIGGER username_check ON staff RENAME TO check_username;
Output:
👁 ImageTo verify the changes, you can check the list of triggers on the 'staff' table:
SELECT tgname FROM pg_trigger WHERE tgrelid = 'staff'::regclass;
This query will return the list of triggers associated with the 'staff' table, allowing you to confirm that the trigger has been renamed successfully.
- The
ALTER TRIGGERstatement in PostgreSQL is primarily used for renaming triggers.- To execute the
ALTER TRIGGERstatement, you need ownership of the table on which the trigger is defined.- PostgreSQL does not guarantee the order in which triggers of the same type (e.g., multiple
BEFORE INSERTtriggers) will fire.- If your database has multiple schemas, remember that trigger names are unique within a schema but not across the entire database.