Sub topic 15
Managing PostgreSQL Triggers: Disable, Replace, Drop, and Inspect
This chapter assumes basic SQL, simple PL/pgSQL, PostgreSQL transactions, and a trigger such as accounts_audit_trg already exists. Trigger management changes database behavior, so inspect the current definition before changing it.
Inspecting triggers
PostgreSQL stores trigger metadata in the pg_trigger system catalog. The pg_get_triggerdef function turns the stored definition into readable SQL.
SELECT
t.tgname AS trigger_name,
t.tgenabled AS enabled_mode,
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;The tgenabled value describes when a trigger runs:
| Value | Meaning |
|---|---|
| `O` | Enabled during normal operations |
| `D` | Disabled |
| `R` | Enabled only for replica-mode sessions |
| `A` | Always enabled |
A trigger definition also shows its event, timing, and granularity. For example, AFTER UPDATE ON accounts FOR EACH ROW runs after each updated row.
Disabling and enabling
Disable one trigger by name:
ALTER TABLE accounts
DISABLE TRIGGER accounts_audit_trg;Enable it again:
ALTER TABLE accounts
ENABLE TRIGGER accounts_audit_trg;Disabling a trigger does not remove it. PostgreSQL keeps the trigger definition, but skips it while it is disabled. Use this for a controlled maintenance operation, then re-enable it immediately.
You can also use DISABLE TRIGGER USER or DISABLE TRIGGER ALL. These affect multiple triggers and can bypass important validation or auditing. They require extra privileges in some cases, so prefer naming one trigger whenever possible.
Replacing and dropping
A trigger calls a function. You can change that function without removing the trigger:
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;The new function body is used by the existing trigger on the next matching operation. Test the function carefully because every attached trigger uses the changed behavior.
To replace a trigger definition, use a transaction so the old definition is removed and the new one is installed as one unit:
BEGIN;
DROP TRIGGER IF EXISTS accounts_audit_trg ON accounts;
CREATE TRIGGER accounts_audit_trg
AFTER INSERT OR UPDATE OR DELETE ON accounts
FOR EACH ROW
EXECUTE FUNCTION audit_accounts();
COMMIT;DROP TRIGGER removes only the trigger, not its function. Use DROP FUNCTION separately, and only after confirming that no other trigger depends on it.
Firing order and safe changes
When several triggers have the same timing and event, PostgreSQL fires them in alphabetical order by trigger name. Do not rely on accidental names for critical dependencies. Combine dependent work into one function or use clearly documented names.
Exercise
Does DROP TRIGGER delete the trigger function too?
Show answer
No. It removes the trigger attachment. The function remains until you explicitly drop it.