CTE Inserts Parent And Child Rows

Write one order header and its line items in a single statement by chaining INSERT RETURNING through a data-modifying CTE for atomic parent-child inserts.

SqlData Integrity

Code

snippet
CREATE TABLE orders (
    id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer   text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE order_items (
    order_id bigint NOT NULL REFERENCES orders(id),
    sku      text NOT NULL,
    qty      int  NOT NULL CHECK (qty > 0)
);

-- 一条语句完成:头表 RETURNING 的 identity 主键直接喂给明细表插入
-- data-modifying CTE 与顶层查询同属一个语句,整体原子,不会产生孤儿明细
WITH new_order AS (
    INSERT INTO orders (customer)
    VALUES ('alice')
    RETURNING id
)
INSERT INTO order_items (order_id, sku, qty)
SELECT n.id, items.sku, items.qty
FROM new_order n,
     (VALUES ('kbd-101', 2), ('mouse-404', 1)) AS items(sku, qty);

How the snippet works

SELECT / INSERT / CREATE statements share the script, touching orders, order_items and new_order.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; 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 keeping child rows pointed at the parent table.

Applying it

Point it at the orders table.

Statements that matter

WITH new_order AS (
    INSERT INTO orders (customer)
    VALUES ('alice')
    RETURNING id
)
INSERT INTO order_items (order_id, sku, qty)
SELECT n.id, items.sku, items.qty
FROM new_order n,
     (VALUES ('kbd-101', 2), ('mouse-404', 1)) AS items(sku, qty);
CREATE TABLE orders (
    id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer   text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE order_items (
    order_id bigint NOT NULL REFERENCES orders(id),
    sku      text NOT NULL,
    qty      int  NOT NULL CHECK (qty > 0)
);

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
The references are `orders`, `order_items`, `new_order`.