Sub topic 10
Rejecting Bad Data with a PostgreSQL Trigger
Assume you know basic INSERT, UPDATE, and CREATE TABLE syntax, transactions, and simple PL/pgSQL blocks. This chapter uses a row-level BEFORE trigger to reject invalid account balances.
A trigger is database code that runs automatically when a table event occurs. A CHECK constraint is usually better for a simple rule about one row:
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
balance numeric(12, 2) NOT NULL
);
ALTER TABLE accounts
ADD CONSTRAINT accounts_balance_nonnegative
CHECK (balance >= 0);Use a trigger when validation needs procedural logic, a custom error, or information that a simple constraint cannot express. For example, a trigger can compare the old and new row, call a function, or inspect related data.
Writing the validation trigger
A PL/pgSQL trigger function must return trigger. It receives the proposed row in NEW. For an update, OLD contains the stored row. If the proposed balance is negative, RAISE EXCEPTION stops the statement.
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();UPDATE OF balance means the trigger is selected when an UPDATE statement names balance. An update of only email does not call this trigger. FOR EACH ROW calls the function once for every affected row.
| Trigger choice | Effect in this example |
|---|---|
| `BEFORE` | Validate before PostgreSQL writes the row |
| `INSERT OR UPDATE OF balance` | Check new rows and balance changes |
| `FOR EACH ROW` | Inspect each proposed row |
| `RETURN NEW` | Permit the row when validation succeeds |
| `RAISE EXCEPTION` | Reject the current statement |
What happens on failure
INSERT INTO accounts (email, balance)
VALUES ('[email protected]', 25.00);
UPDATE accounts
SET balance = -5.00
WHERE email = '[email protected]';The INSERT succeeds. The UPDATE raises a check_violation error, so PostgreSQL does not store the negative balance. If one statement updates many rows and the trigger rejects one of them, the statement fails as a whole. Within a transaction, the transaction may then need a rollback or savepoint before more work can continue.
A trigger is useful when the rule changes data, needs branching, or must produce a domain-specific error. It is not a substitute for authorization checks. Application permissions and database privileges still control who may attempt the operation.
Exercise
What happens when an UPDATE changes only the email column, while the trigger is defined with UPDATE OF balance?
Show answer
PostgreSQL does not select this trigger for that statement, so the trigger function is not called. A separate constraint still checks the final row if one exists.