Sub topic 8
What the Return Value Does
Assume you know basic INSERT, UPDATE, DELETE, transactions, and simple PL/pgSQL. In PostgreSQL, a trigger function returns a value of type trigger. That value tells PostgreSQL whether to continue the operation and, for some triggers, which row to use.
BEFORE row-level triggers
A BEFORE trigger can inspect or change NEW before PostgreSQL writes it.
RETURN NEWcontinues the operation. PostgreSQL writes the returned row.RETURN NULLskips the operation for the current row.RETURN OLDuses the previous row value where that makes sense, such as anUPDATEorDELETE.
The most common pattern is to change NEW, then return it.
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
balance numeric(12, 2) NOT NULL
);
CREATE FUNCTION prevent_negative_balance()
RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.balance < 0 THEN
RETURN NULL;
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER accounts_balance_check
BEFORE INSERT OR UPDATE ON accounts
FOR EACH ROW
EXECUTE FUNCTION prevent_negative_balance();Here, an insert or update with a negative balance is silently skipped. For validation that should tell the client why the operation failed, raise an exception instead.
AFTER and statement-level triggers
An AFTER trigger runs after the row change has been accepted. Its return value is ignored. Return NULL by convention:
CREATE FUNCTION record_change()
RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'Operation: %', TG_OP;
RETURN NULL;
END;
$$;The same rule applies to statement-level triggers. They do not represent one particular row, so NEW and OLD are unavailable. Their return value cannot change the statement's result.
INSTEAD OF triggers
An INSTEAD OF trigger is used on a view. It replaces the requested operation with code in the trigger function.
For a row-level INSTEAD OF trigger:
- Return a non-null row, usually
NEW, to report that the operation was handled. - Return
NULLto skip the operation for that view row.
The returned row can also become the row reported by INSERT, UPDATE, or DELETE ... RETURNING.
A quick decision guide
| Trigger kind | `RETURN NEW` | `RETURN NULL` |
|---|---|---|
| `BEFORE` row-level | Continue using `NEW` | Skip this row |
| `AFTER` row-level | Ignored | Conventional |
| Statement-level | Ignored | Conventional |
| `INSTEAD OF` row-level | Report operation handled | Skip this row |
Exercise
A BEFORE UPDATE trigger changes NEW.balance to 0 but returns OLD. Which balance is written?
Show answer
The returned row is used, so the old row value is used. The change to NEW is discarded.