// strings reference

SQL XMLTABLE function

FROM XMLTABLE('/order/items/item' PASSING doc COLUMNS (...)) flattens repeating XML nodes into rows. XML's answer to JSON_TABLE.

Kategorie
Strings
Returns
rowset
In this category
164 of 172

Syntax

XMLTABLE(row_pattern PASSING doc COLUMNS col type PATH 'subpath', ...)

Engine-Unterstützung

EngineSupportNotizen
SQL Server Not built in no XMLTABLE; CROSS APPLY doc.nodes() with .value(), or OPENXML
PostgreSQL Ja PostgreSQL 10+
MySQL Not built in no XML support
SQLite Not built in no XML support
Oracle Ja XMLTABLE with the same COLUMNS clause

Beispiele

PostgreSQL

SELECT xt.sku, xt.qty
FROM imports i,
XMLTABLE('/order/items/item'
  PASSING i.doc
  COLUMNS sku text PATH 'sku',
          qty int PATH 'qty') xt;

Oracle

SELECT xt.sku, xt.qty
FROM imports i,
XMLTABLE('/order/items/item'
  PASSING i.doc
  COLUMNS sku VARCHAR2(40) PATH 'sku',
          qty NUMBER PATH 'qty') xt;

Gut zu wissen

  • The row pattern selects the repeating nodes; each column's PATH is relative to it. Namespaced documents need an XMLNAMESPACES clause before the row pattern.
  • The column list is not parenthesised: COLUMNS sku text PATH 'sku', qty int PATH 'qty'. Copying JSON_TABLE's COLUMNS (...) shape is a syntax error on both PostgreSQL and Oracle.
  • PASSING correlates outer columns: XMLTABLE('...' PASSING i.doc ...) shreds each row's own document, the per-row pattern you almost always want.
  • Without a PATH, a column reads the child element with the column's own name, so COLUMNS sku text, qty int works when the names match.

Questions about XMLTABLE

How do I shred XML to rows on SQL Server?

CROSS APPLY the .nodes() method and read each node with .value(): FROM t CROSS APPLY t.doc.nodes('/order/items/item') AS x(n), then x.n.value('(sku)[1]', 'nvarchar(40)'). OPENXML still works but needs sp_xml_preparedocument first.

XMLTABLE or JSON_TABLE?

Same design, different input format: XMLTABLE for XML on PostgreSQL and Oracle, JSON_TABLE for JSON on Oracle, MySQL and PostgreSQL 17. Note the COLUMNS list is parenthesised in JSON_TABLE and not in XMLTABLE.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.