Sub topic 12
INSTEAD OF Triggers on Views
Prerequisites: You should know basic CREATE VIEW, INSERT, and PL/pgSQL syntax. You should also understand that a transaction either commits all its changes or rolls them back.
A view is a saved query that presents data from one or more tables. Some simple views are automatically updatable, but a view containing joins, aggregates, or computed values often cannot receive direct INSERT, UPDATE, or DELETE statements.
An INSTEAD OF trigger supplies the missing behavior. PostgreSQL runs the trigger function instead of attempting the operation on the view. The function then writes to the underlying tables as appropriate.
A worked INSERT example
The following view exposes only account identifiers and email addresses. The trigger makes the view accept inserts.
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
balance numeric(12,2) NOT NULL DEFAULT 0,
updated_at timestamptz NOT NULL DEFAULT now()
);
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();
INSERT INTO account_emails (email)
VALUES ('[email protected]');NEW represents the row requested by the client. The function copies its email into accounts, retrieves the generated identifier, and returns the completed view row.
An INSTEAD OF trigger must be a row-level trigger. PostgreSQL does not support FOR EACH STATEMENT for this trigger timing. You can create separate INSTEAD OF triggers for INSERT, UPDATE, and DELETE, each implementing the corresponding operation on the base tables.
| Trigger timing | Typical purpose | Return value |
|---|---|---|
| `INSTEAD OF` | Replace an operation on a view | A non-null row reports that the operation was handled |
Returning NULL tells PostgreSQL that this row was not processed. Returning a non-null NEW or OLD row reports that the operation succeeded. For an INSERT, return NEW; for a DELETE, return OLD.
An automatically updatable view is simpler when PostgreSQL can provide the needed behavior. Prefer that option when no custom translation or validation is required.
Exercise
What should an INSTEAD OF INSERT trigger function return after it inserts the requested row into the base table?
Show answer
It should return a non-null NEW row, usually after filling generated values such as the new identifier.