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.
Code
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Name the tables involved in this file.
- The references are `accounts`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.