Sub topic 15
Managing Triggers: Disable, Replace, Drop, Inspect
This chapter covers the maintenance side of triggers: finding out what exists, turning triggers off and on, changing them, and removing them. It assumes you can already write a trigger function and attach it with CREATE TRIGGER, and that you understand transactions. The examples use the accounts table and the accounts_audit_trg trigger from earlier chapters.
Inspecting triggers
The catalog pg_trigger has one row per trigger. Internal triggers, such as those PostgreSQL creates to enforce foreign keys, have tgisinternal = true. Filter them out to see only your own.
SELECT t.tgname,
t.tgenabled,
t.tgfoid::regproc AS function_name,
pg_get_triggerdef(t.oid) AS definition
FROM pg_trigger AS t
WHERE t.tgrelid = 'accounts'::regclass
AND NOT t.tgisinternal
ORDER BY t.tgname;pg_get_triggerdef(oid) rebuilds the full CREATE TRIGGER statement. That makes it a quick way to see timing, events, WHEN conditions, and column lists in one place. To see the function body, call pg_get_functiondef('set_updated_at'::regproc).
In psql, \d accounts lists the table's triggers at the bottom. Disabled triggers appear in a separate "Disabled user triggers" section, so a disabled trigger is easy to spot there.
The tgenabled column is a single character:
| Value | Meaning | Fires when `session_replication_role` is |
|---|---|---|
| `O` | Enabled (origin), the default | `origin` or `local` |
| `D` | Disabled | never |
| `R` | Enabled replica | `replica` |
| `A` | Enabled always | any setting |
To find triggers that someone disabled and forgot about, run a database-wide check:
SELECT tgrelid::regclass AS table_name, tgname
FROM pg_trigger
WHERE tgenabled = 'D'
AND NOT tgisinternal;Disabling and enabling
ALTER TABLE changes a trigger's state. You do not use ALTER TRIGGER for this.
ALTER TABLE accounts DISABLE TRIGGER accounts_audit_trg;
ALTER TABLE accounts ENABLE TRIGGER accounts_audit_trg;
ALTER TABLE accounts ENABLE REPLICA TRIGGER accounts_audit_trg;
ALTER TABLE accounts ENABLE ALWAYS TRIGGER accounts_audit_trg;Instead of a name, you can write USER to affect every non-internal trigger on the table, or ALL to include internal ones too. DISABLE TRIGGER ALL turns off foreign key enforcement, so it requires superuser rights. Hosted services that do not give you a superuser role will reject it.
Three properties of disabling matter in practice:
- It is global and persistent. The change applies to every session and survives restarts until someone re-enables the trigger. It is not a per-session switch.
- It is transactional. If you roll back the transaction, the trigger returns to its previous state.
- It takes a strong lock.
ENABLEandDISABLE TRIGGERtake aSHARE ROW EXCLUSIVElock on the table, which blocks concurrent writes until your transaction ends.
Because of these properties, wrap the disable and enable in one transaction around the work:
BEGIN;
ALTER TABLE accounts DISABLE TRIGGER accounts_audit_trg;
UPDATE accounts SET email = lower(email);
ALTER TABLE accounts ENABLE TRIGGER accounts_audit_trg;
COMMIT;If the UPDATE fails, the whole block rolls back and the trigger stays enabled. Keep the transaction short, since other writers wait on the table lock.
Disabling a trigger does not repair anything. Rows changed while it was off never reach the audit table, and an updated_at trigger that was off leaves stale timestamps. Decide how to backfill before you disable.
Skipping triggers for one session
A superuser can change session_replication_role to skip ordinary triggers for the current session only:
SET session_replication_role = replica;
-- bulk load here: triggers in state O and foreign key triggers do not fire
RESET session_replication_role;Only triggers in state R or A fire while the role is replica. This setting also suppresses foreign key checks, so use it only with data you already trust. Logical replication subscribers use this mechanism to avoid re-running triggers for replicated changes.
Replacing a trigger
From PostgreSQL 14, CREATE OR REPLACE TRIGGER redefines a trigger of the same name on the same table, or creates it if none exists:
CREATE OR REPLACE TRIGGER accounts_set_updated_at
BEFORE UPDATE ON accounts
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE FUNCTION set_updated_at();On older versions, drop and create the trigger inside one transaction so no write slips through unprotected:
BEGIN;
DROP TRIGGER IF EXISTS accounts_set_updated_at ON accounts;
CREATE TRIGGER accounts_set_updated_at
BEFORE UPDATE ON accounts
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();
COMMIT;To change what the trigger does without touching its definition, replace the function instead. Every trigger that uses the function picks up the new body:
CREATE OR REPLACE FUNCTION set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := clock_timestamp();
RETURN NEW;
END;
$$;CREATE OR REPLACE FUNCTION cannot change the return type. A trigger function must keep returning trigger.
Renaming and dropping
ALTER TRIGGER accounts_audit_trg ON accounts RENAME TO accounts_z_audit;
DROP TRIGGER accounts_z_audit ON accounts;
DROP TRIGGER IF EXISTS accounts_z_audit ON accounts;A rename is not cosmetic. Triggers for the same event and timing fire in alphabetical order of their names, so renaming one can change which runs first.
Dropping has some side effects to know about:
DROP TRIGGERneeds the table name, because trigger names are only unique per table.DROP TABLEremoves its triggers automatically, but the trigger functions stay behind as ordinary functions.DROP FUNCTIONfails while any trigger uses the function.DROP FUNCTION ... CASCADEsucceeds and silently drops those triggers too, so checkpg_triggerfirst.
Permissions
You must own a table to disable, enable, rename, or drop its triggers. Creating a trigger requires the TRIGGER privilege on the table and EXECUTE on the function. Ownership applies to the table, so you cannot manage a trigger on someone else's table just because you wrote its function.
Exercise
A nightly job runs "BEGIN; ALTER TABLE accounts DISABLE TRIGGER accountsaudittrg; ...bulk update...; COMMIT;" and the bulk update raises an error halfway through. The next morning, is the audit trigger enabled? Also, what query would you run to find every disabled non-internal trigger in the database?
Show answer
Yes, it is enabled. Disabling a trigger is transactional, so the error aborts the transaction and the ALTER TABLE is rolled back along with everything else. To find disabled triggers, run: SELECT tgrelid::regclass, tgname FROM pg_trigger WHERE tgenabled = 'D' AND NOT tgisinternal;
Exercise
You rename a trigger from accountsaudittrg to accountsaaudit on a table that also has a BEFORE UPDATE trigger named accountssetupdated_at. Why might this change behavior, and what name would you pick to keep the original order?
Show answer
Triggers of the same timing and event fire in alphabetical order by name. If the renamed trigger has the same timing and event as another, its position in that order can change. Here the audit trigger is AFTER and the other is BEFORE, so the order between them is unaffected, since BEFORE triggers always fire before AFTER triggers. Among triggers of the same timing, pick a name that sorts where you want it, for example a name starting with a later letter to run last.