PL/pgSQL EXCEPTION Blocks Roll Back Subtransactions

Handle errors inside a PL/pgSQL EXCEPTION block: the block runs as a subtransaction, so failed statements roll back without aborting the caller.

SqlResilience

Code

snippet
-- EXCEPTION 块会创建子事务:出错只回滚块内语句
CREATE OR REPLACE FUNCTION transfer(from_id bigint, to_id bigint, amount numeric)
RETURNS text
LANGUAGE plpgsql
AS $$
BEGIN
  UPDATE accounts SET balance = balance - amount WHERE id = from_id;
  IF NOT FOUND THEN
    RAISE EXCEPTION 'missing source account %', from_id;
  END IF;

  UPDATE accounts SET balance = balance + amount WHERE id = to_id;
  RETURN 'committed';
EXCEPTION
  WHEN foreign_key_violation OR check_violation THEN
    -- 子事务回滚,两条 UPDATE 都不会生效
    RETURN 'rejected: constraint';
  WHEN raise_exception THEN
    RETURN 'rejected: missing account';
END;
$$;

-- 调用:错误被函数内部处理,外层事务仍可继续
SELECT transfer(1, 999, 50.00) AS outcome;
SELECT transfer(1, 2, 50.00) AS outcome;

-- 在 PL/pgSQL 内可用 GET DIAGNOSTICS 读取 SQLSTATE 与错误文本

How the snippet works

What runs here is SELECT / UPDATE / CREATE — accounts are the objects involved.

Mechanically, the statements are built from: a WHERE clause limiting a statement to the rows that qualify.

Applying it

The accounts table is the working surface here.

Statements that matter

SELECT transfer(1, 999, 50.00) AS outcome;
SELECT transfer(1, 2, 50.00) AS outcome;

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
The references are `accounts`.