Sub topic 10
Example: rejecting bad data
A trigger can stop a write before it reaches the table. This chapter builds a validation trigger, shows how its error behaves, and explains when a plain CHECK constraint is the better choice. It assumes you can write a basic PL/pgSQL function and know how NEW and OLD work in a row-level trigger.
The rule and the trigger
The accounts table from earlier chapters has a balance column. The rule is that a balance must never be negative. The trigger function inspects the incoming row and raises an exception if the rule is broken.
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 FUNCTION forbid_negative_balance() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.balance < 0 THEN
RAISE EXCEPTION 'balance cannot be negative: %', NEW.balance
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER accounts_check_balance
BEFORE INSERT OR UPDATE OF balance ON accounts
FOR EACH ROW
EXECUTE FUNCTION forbid_negative_balance();Each part of the trigger definition has a reason:
- BEFORE timing. The check runs before the row is stored, so a bad row is never written. An
AFTERtrigger would also abort the statement, but only after the work was done. - FOR EACH ROW. The rule looks at one row's value, so the function needs
NEWfor each row. - INSERT OR UPDATE OF balance. An insert can supply a bad balance. An update only matters if it assigns
balance. AnUPDATE accounts SET email = ...skips this trigger entirely. - RETURN NEW. In a
BEFORErow trigger, returningNEWtells PostgreSQL to go ahead and write that row.
What the caller sees
Try the trigger in psql:
INSERT INTO accounts (email, balance) VALUES ('[email protected]', 100);
UPDATE accounts SET balance = balance - 250 WHERE email = '[email protected]';The first statement succeeds. The second fails:
ERROR: balance cannot be negative: -150.00
CONTEXT: PL/pgSQL function forbid_negative_balance() line 4 at RAISEThree behaviors are worth knowing.
- The whole statement fails, not just one row. If an
UPDATEtouches 1,000 rows and row 700 violates the rule, none of the 1,000 changes persist. - The enclosing transaction becomes aborted. Inside
BEGIN ... COMMIT, every later command fails with "current transaction is aborted" until youROLLBACK. To continue after an expected failure, wrap the statement in aSAVEPOINTand roll back to it. - The error code is under your control.
ERRCODE = 'check_violation'is SQLSTATE23514, the same code a realCHECKconstraint raises. Application code that handles constraint errors then handles this one too. WithoutUSING ERRCODE, the code defaults toP0001(raise_exception).
Making the error more useful
RAISE accepts more fields than a message. They let a client show the problem next to the right field:
CREATE OR REPLACE FUNCTION forbid_negative_balance() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.balance < 0 THEN
RAISE EXCEPTION 'balance cannot be negative: %', NEW.balance
USING ERRCODE = 'check_violation',
DETAIL = format('Account %s would go from %s to %s.',
NEW.id, OLD.balance, NEW.balance),
HINT = 'Reduce the withdrawal amount.',
COLUMN = 'balance',
TABLE = TG_TABLE_NAME;
END IF;
RETURN NEW;
END;
$$;This version has a bug: during an INSERT, OLD is not assigned, and reading OLD.balance raises an error about record "old" is not assigned yet (in PostgreSQL 11 and earlier, the trigger fails at definition time or first use). The trigger fires on INSERT OR UPDATE, so the function must branch on TG_OP before touching OLD:
CREATE OR REPLACE FUNCTION forbid_negative_balance() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.balance < 0 THEN
RAISE EXCEPTION 'balance cannot be negative: %', NEW.balance
USING ERRCODE = 'check_violation',
DETAIL = CASE WHEN TG_OP = 'UPDATE'
THEN format('Account %s would go from %s to %s.',
NEW.id, OLD.balance, NEW.balance)
ELSE format('Initial balance was %s.', NEW.balance)
END,
HINT = 'Reduce the withdrawal amount.',
COLUMN = 'balance',
TABLE = TG_TABLE_NAME;
END IF;
RETURN NEW;
END;
$$;CREATE OR REPLACE FUNCTION swaps the body without touching the trigger that already points at it.
Edge cases
- NULL passes silently.
NULL < 0evaluates to NULL, andIFtreats NULL as false. HereNOT NULLon the column blocks nulls separately. If a nullable column needs a rule, test it explicitly withIS NULLor writeIF NOT (NEW.x >= 0). - Other triggers can change the row first. Triggers on one event fire in alphabetical order by name, and each
BEFOREtrigger sees the row as the previous one left it. Name validation triggers so they run after any trigger that normalizes the data, for examplez_validate_..., or keep both steps in one function. - Silently skipping is different from rejecting. Returning
NULLfrom aBEFORErow trigger skips that row with no error. That is occasionally wanted, but for validation it hides data loss. Raise an exception instead. - Disabled triggers, bulk loads, and
TRUNCATE.ALTER TABLE ... DISABLE TRIGGER, andsession_replication_role = replica, switch the rule off.COPYfires row triggers, but aTRUNCATEdoes not fire row triggers at all. A rule that must always hold needs a constraint.
Trigger or CHECK constraint?
For this particular rule, a constraint is better:
ALTER TABLE accounts
ADD CONSTRAINT balance_nonnegative CHECK (balance >= 0);A CHECK is declarative, shows up in \d accounts, is validated on existing rows when added, and cannot be switched off per trigger. Prefer it whenever the rule depends only on the columns of the one row.
Reach for a trigger when the rule needs something a CHECK cannot do:
| Need | Why a trigger |
|---|---|
| Compare to another table | `CHECK` cannot run subqueries |
| Compare `OLD` and `NEW` (for example, a status that may only move forward) | `CHECK` sees only the new row |
| Custom error details or messages | Full control over `RAISE` fields |
| Rules that depend on the operation or the current user | `TG_OP` and `current_user` are available |
Exercise
A trigger is defined as BEFORE UPDATE OF balance ON accounts FOR EACH ROW and raises an exception when NEW.balance < 0. A client runs UPDATE accounts SET email = '[email protected]' WHERE id = 7, and account 7 already holds a negative balance written before the trigger existed. Does the statement succeed, and why? What changes if the trigger is replaced by a CHECK constraint added with ALTER TABLE ... ADD CONSTRAINT?
Show answer
The statement succeeds. UPDATE OF balance fires only when balance appears in the SET list, and this statement sets only email, so the function never runs. A CHECK constraint is different: ADD CONSTRAINT validates all existing rows, so it would fail at creation time because of the negative balance (unless added as NOT VALID). Once it exists, it is checked on every row an UPDATE writes, even if the UPDATE does not name balance, so the email update would also fail until the balance is fixed.