Data-Modifying CTE Atomic Chain

Chain INSERT RETURNING output into an UPDATE within one data-modifying CTE statement so order creation and stock deduction commit atomically together.

SqlData Integrity

Code

snippet
-- 示意表:库存与订单
CREATE TABLE inventory (
    sku text PRIMARY KEY,
    available integer NOT NULL CHECK (available >= 0),
    reserved integer NOT NULL DEFAULT 0
);

CREATE TABLE orders (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    sku text NOT NULL REFERENCES inventory (sku),
    qty integer NOT NULL CHECK (qty > 0),
    customer_id bigint NOT NULL,
    created_at timestamptz NOT NULL DEFAULT NOW()
);

INSERT INTO inventory (sku, available) VALUES ('desk-lamp', 10);

-- 一条语句原子完成:写订单 → 扣库存 → 汇总结果。
-- WITH 里的子语句彼此看不到对方对目标表的写入,但都能引用上一个 CTE 的 RETURNING 输出
WITH new_order AS (
    INSERT INTO orders (sku, qty, customer_id)
    VALUES ('desk-lamp', 2, 501)
    RETURNING id AS order_id, sku, qty
),
stocked AS (
    UPDATE inventory AS inv
    SET reserved = inv.reserved + o.qty,
        available = inv.available - o.qty
    FROM new_order AS o
    WHERE inv.sku = o.sku
    RETURNING inv.sku, inv.available
)
SELECT no.order_id, no.sku, no.qty, st.available AS remaining
FROM new_order AS no
JOIN stocked AS st ON st.sku = no.sku;

What the code does

Several statements share this file — SELECT / INSERT / UPDATE / CREATE, with inventory, orders, new_order and stocked among the objects involved.

In terms of clauses, the statements use: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause narrowing which rows one statement affects; a RETURNING clause that hands the affected rows back to the caller; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value; a foreign-key REFERENCES guard tying rows to the parent table.

Using it

The inventory table is the working surface here.

Key statements

CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL REFERENCES inventory (sku),
qty integer NOT NULL CHECK (qty > 0),
customer_id bigint NOT NULL,
created_at timestamptz NOT NULL DEFAULT NOW()
);
CREATE TABLE inventory (
sku text PRIMARY KEY,
available integer NOT NULL CHECK (available >= 0),
reserved integer NOT NULL DEFAULT 0
);
INSERT INTO inventory (sku, available) VALUES ('desk-lamp', 10);

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`inventory`, `orders`, `new_order`, `stocked` — joined via one JOIN clause.