XMLTABLE Unpacks XML Elements Into Rows

Shred XML documents into typed relational columns with XMLTABLE, extracting attributes, defaults, NOT NULL checks, and FOR ORDINALITY numbers.

SqlData Fetching

Code

snippet
CREATE TEMP TABLE invoice_batches (
    batch_id integer PRIMARY KEY,
    payload  xml NOT NULL
);

INSERT INTO invoice_batches VALUES (
    1,
    XMLPARSE(DOCUMENT '<orders>
        <order id="101"><customer>Ada</customer><coupon>VIP10</coupon></order>
        <order id="102"><customer>Linus</customer></order>
    </orders>')
);

SELECT
    b.batch_id,
    x.line_no,
    x.order_id,
    x.customer,
    x.coupon
FROM invoice_batches b,
XMLTABLE(
    '/orders/order'
    PASSING b.payload
    COLUMNS
        line_no  FOR ORDINALITY,
        order_id integer PATH '@id',
        customer text    PATH 'customer' NOT NULL,
        coupon   text    PATH 'coupon' DEFAULT 'NONE'
) AS x
ORDER BY b.batch_id, x.line_no;

Annotated execution — XMLTABLE Unpacks XML Elements Into Rows

What runs here is SELECT / INSERT / CREATE — invoice_batches are the objects involved.

invoice_batches prepares disposable temporary relations scoped to the connection directly above the queries so cleanup finishes automatically when exiting.

The pieces that do the work: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Applying it

It carries its own setup: the session-local tables in play (invoice_batches) come from the file’s statements — run the entire file against a disposable database.

Statements that matter

INSERT INTO invoice_batches VALUES (
    1,
    XMLPARSE(DOCUMENT '<orders>
        <order id="101"><customer>Ada</customer><coupon>VIP10</coupon></order>
        <order id="102"><customer>Linus</customer></order>
    </orders>')
);
CREATE TEMP TABLE invoice_batches (
    batch_id integer PRIMARY KEY,
    payload  xml NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`invoice_batches` — referenced directly, no join needed.