Sub topic 3
INSTEAD OF triggers on views
This chapter assumes you know basic SQL, can create tables and views, and have written simple PL/pgSQL (DECLARE, BEGIN, IF, RAISE).
INSTEAD OF triggers on views
A view stores no rows, so PostgreSQL can write through a view only when the view is simple enough. An INSTEAD OF trigger replaces the write with your function, which decides what changes in the underlying tables.
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL
);
CREATE VIEW account_emails AS
SELECT id, email FROM accounts;
CREATE FUNCTION account_emails_insert() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO accounts (email) VALUES (NEW.email)
RETURNING id INTO NEW.id;
RETURN NEW;
END;
$$;
CREATE TRIGGER account_emails_ins
INSTEAD OF INSERT ON account_emails
FOR EACH ROW
EXECUTE FUNCTION account_emails_insert();Transition tables for set-based statement triggers
A statement-level AFTER trigger fires once per statement. Add REFERENCING OLD TABLE AS name or NEW TABLE AS name to read every affected row in one query, which avoids a function call per row.
Several triggers on the same event
PostgreSQL fires triggers in alphabetical order by name. For one event, the order is statement-level BEFORE, row-level BEFORE, the row change, row-level AFTER, then statement-level AFTER. Name triggers with a prefix (for example 10_, 20_) when order matters.
Managing triggers: disable, replace, drop, inspect
ALTER TABLE accounts DISABLE TRIGGER accounts_audit_trg;
ALTER TABLE accounts ENABLE TRIGGER accounts_audit_trg;
DROP TRIGGER IF EXISTS accounts_audit_trg ON accounts;
SELECT tgname, tgenabled
FROM pg_trigger
WHERE tgrelid = 'accounts'::regclass AND NOT tgisinternal;From PostgreSQL 14, CREATE OR REPLACE TRIGGER replaces a trigger's definition in one step.
Recursion, cascades, and common pitfalls
A trigger that updates its own table fires itself again. A trigger that writes to another table fires that table's triggers too, which is a cascade. Guard against loops with a WHEN condition or by checking pg_trigger_depth(), which returns the current nesting level.
Performance costs and alternatives
Row-level triggers call a function once per row, so a bulk update pays that cost on every row. Prefer column defaults, generated columns, CHECK constraints, or foreign keys when they can express the rule.
Constraint triggers and deferred checks
A constraint trigger created with CREATE CONSTRAINT TRIGGER ... DEFERRABLE INITIALLY DEFERRED runs at commit time. It must be an AFTER row-level trigger.
Event triggers for DDL commands
An event trigger fires on DDL such as CREATE TABLE. Its function returns event_trigger, and creating one requires superuser rights.
CREATE FUNCTION log_ddl() RETURNS event_trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'DDL command finished: %', TG_TAG;
END;
$$;
CREATE EVENT TRIGGER log_ddl_trg
ON ddl_command_end
EXECUTE FUNCTION log_ddl();Testing and debugging triggers
Wrap experiments in BEGIN and ROLLBACK so test data does not persist. Use RAISE NOTICE to print TG_OP and TG_NAME. Run EXPLAIN ANALYZE to see the time each trigger consumed.
Exercise
Why does the INSTEAD OF trigger in the first section return NEW instead of NULL?
Show answer
Returning NEW tells PostgreSQL the insert was handled, and the row with the generated id is reported back to the caller. Returning NULL would report the insert as not performed.