Sub topic 6
Flattening nested arrays with NESTED PATH
This chapter assumes you can read basic SQL/JSON path expressions and have used JSON_TABLE with a single row path, as in the previous chapters. It uses the orders table from earlier. It needs Oracle Database 21c or later for the JSON column type. The JSON_TABLE syntax itself also works on 19c with VARCHAR2 or CLOB columns that have an IS JSON constraint.
The problem a single row path cannot solve
A row path such as '$.items[*]' produces one row for each array element. That works well when you only need item fields. An order document also carries order-level data: orderId and the customer name. If you put $.items[*] in the row path, those order-level fields sit outside the context node and are hard to reach.
NESTED PATH solves this. The row path stays at the document root, and the array is declared as a nested clause inside COLUMNS. Oracle repeats the parent columns on every child row.
SELECT jt.*
FROM orders o,
JSON_TABLE(o.doc, '$'
COLUMNS (
order_id NUMBER PATH '$.orderId',
customer VARCHAR2(100) PATH '$.customer.name',
NESTED PATH '$.items[*]'
COLUMNS (
line_no FOR ORDINALITY,
sku VARCHAR2(20) PATH '$.sku',
qty NUMBER PATH '$.qty'
)
)) jt;For order 1001 the result is:
| ORDER_ID | CUSTOMER | LINE_NO | SKU | QTY |
|---|---|---|---|---|
| 1001 | Ada Lovelace | 1 | A-1 | 2 |
| 1001 | Ada Lovelace | 2 | B-7 | 1 |
The paths inside the nested COLUMNS clause are relative to each array element, not to the document root. That is why the nested column uses '$.sku' and not '$.items[*].sku'.
FOR ORDINALITY
FOR ORDINALITY generates a counter column. Inside a NESTED PATH clause, it numbers the elements of that array, starting at 1, and restarts for each parent. It does not need a PATH clause. The counter reflects the array's order in the document, so you can use it to recover line order or to build a stable key such as (order_id, line_no).
You can also put FOR ORDINALITY in the top-level COLUMNS list. There it numbers the rows produced by the row path.
Parents without children are kept
NESTED PATH behaves like a left outer join. If the array is empty or missing, the parent row is still returned, and the nested columns are NULL. Add an order with no items to see it:
INSERT INTO orders (doc) VALUES (
'{"orderId": 1002,
"customer": {"name": "Alan Turing"},
"status": "NEW",
"items": []}'
);Running the earlier query again now also returns this row:
| ORDER_ID | CUSTOMER | LINE_NO | SKU | QTY |
|---|---|---|---|---|
| 1002 | Alan Turing | NULL | NULL | NULL |
If you only want orders that have items, filter in the outer query with WHERE jt.sku IS NOT NULL. You can also filter in the document with JSON_EXISTS, as shown in the chapter on query functions.
Nesting inside nesting
A nested clause can contain another nested clause, so you can flatten arrays of arrays. The next example is self-contained. It passes a JSON string literal straight to JSON_TABLE, so it needs no table.
SELECT jt.*
FROM JSON_TABLE(
'{"orderId": 2001,
"items": [
{"sku": "A-1", "discounts": ["SPRING", "VIP"]},
{"sku": "B-7", "discounts": []}
]}',
'$'
COLUMNS (
order_id NUMBER PATH '$.orderId',
NESTED PATH '$.items[*]'
COLUMNS (
sku VARCHAR2(20) PATH '$.sku',
NESTED PATH '$.discounts[*]'
COLUMNS (
discount VARCHAR2(20) PATH '$'
)
)
)) jt;| ORDER_ID | SKU | DISCOUNT |
|---|---|---|
| 2001 | A-1 | SPRING |
| 2001 | A-1 | VIP |
| 2001 | B-7 | NULL |
The path '$' inside the innermost clause means "the array element itself". It is the correct path for arrays of scalars such as strings and numbers. The outer-join rule applies at each level, so item B-7 is kept even though it has no discounts.
Sibling nested paths are not a cross product
Suppose a document has two independent arrays, items and tags, and you declare a NESTED PATH for each at the same level. You might expect every item to pair with every tag. Oracle does not do that. Sibling nested paths are combined like a union, and the columns of the other sibling are NULL.
SELECT jt.*
FROM JSON_TABLE(
'{"orderId": 3001,
"items": [{"sku": "A-1"}, {"sku": "B-7"}],
"tags": ["gift", "rush", "fragile"]}',
'$'
COLUMNS (
order_id NUMBER PATH '$.orderId',
NESTED PATH '$.items[*]' COLUMNS (sku VARCHAR2(20) PATH '$.sku'),
NESTED PATH '$.tags[*]' COLUMNS (tag VARCHAR2(20) PATH '$')
)) jt;| ORDER_ID | SKU | TAG |
|---|---|---|
| 3001 | A-1 | NULL |
| 3001 | B-7 | NULL |
| 3001 | NULL | gift |
| 3001 | NULL | rush |
| 3001 | NULL | fragile |
The result has 2 + 3 = 5 rows, not 2 × 3 = 6. This avoids a multiplication explosion. It also means a plain SUM over a parent column would count the parent value once for each child row, so aggregate each array separately.
Aggregating the flattened rows
Once the arrays are rows, normal SQL applies. This query computes the total of each order. Order 1002 has no items, so its total is NULL. The query uses NVL to turn that into 0.
SELECT jt.order_id,
NVL(SUM(jt.qty * jt.price), 0) AS order_total
FROM orders o,
JSON_TABLE(o.doc, '$'
COLUMNS (
order_id NUMBER PATH '$.orderId',
NESTED PATH '$.items[*]'
COLUMNS (
qty NUMBER PATH '$.qty',
price NUMBER PATH '$.price'
)
)) jt
GROUP BY jt.order_id;For order 1001, the total is 2 × 9.5 + 1 × 24 = 43.
Common errors and how to read them
- Forgetting
[*].NESTED PATH '$.items'points at the array as a single value. The nested columns then look for$.skuon the array itself and returnNULL. Use'$.items[*]'to visit each element. - Using absolute paths in nested columns. Inside a nested clause,
'$.items[*].sku'fails to match anything. Paths are relative to the current array element. - Duplicate column names. Column names must be unique across the whole
JSON_TABLE, including nested clauses. Two nested clauses that both definenameraise an error. Rename one of them. - Truncated or mismatched types. A
VARCHAR2(5)column holding"Ada Lovelace"returnsNULLby default, because the default error handling isNULL ON ERROR. Size string columns generously. AddERROR ON ERRORwhile developing so that problems fail loudly instead of becomingNULL. - Expecting a cross product. As shown above, sibling arrays are unioned. If you need the pairing of two arrays, put one inside the other, or join two separate
JSON_TABLEcalls. - Counting rows as orders. After flattening,
COUNT(*)counts item rows. UseCOUNT(DISTINCT order_id)to count orders.
Performance notes
JSON_TABLE runs once for each row of the base table. It parses or navigates every document it receives. Filter the base table first, for example with JSON_EXISTS or an indexed JSON_VALUE predicate, so that fewer documents reach JSON_TABLE. The indexing chapter covers those indexes. If you flatten the same arrays in many queries, consider a view over the JSON_TABLE query so the column definitions live in one place.
Exercise
Using the orders table, write a query that returns one row per item with columns orderid, lineno, sku and line_total (qty times price). Orders with no items must still appear, with NULL in the item columns. Then say what changes if you replace NESTED PATH '$.items[*]' with a row path of '$.items[*]' and read orderId using PATH '$.orderId'.
Show answer
SELECT jt. FROM orders o, JSONTABLE(o.doc, '$' COLUMNS (orderid NUMBER PATH '$.orderId', NESTED PATH '$.items[]' COLUMNS (lineno FOR ORDINALITY, sku VARCHAR2(20) PATH '$.sku', linetotal NUMBER PATH '$.qty $.price'))) jt; is not valid, because paths cannot hold arithmetic. Read qty and price as separate columns and compute the product in the outer SELECT: SELECT jt.orderid, jt.lineno, jt.sku, jt.qty jt.price AS linetotal FROM orders o, JSONTABLE(o.doc, '$' COLUMNS (orderid NUMBER PATH '$.orderId', NESTED PATH '$.items[*]' COLUMNS (lineno FOR ORDINALITY, sku VARCHAR2(20) PATH '$.sku', qty NUMBER PATH '$.qty', price NUMBER PATH '$.price'))) jt; Order 1002 appears with NULL item columns because NESTED PATH keeps parents without children. With the row path '$.items[*]', the context is each item, so '$.orderId' no longer matches anything and returns NULL. Items would be returned, but order 1002 would produce no row at all.
Exercise
A document has "items": [{"sku": "A-1"}, {"sku": "B-7"}] and "tags": ["x", "y", "z"]. You declare two sibling NESTED PATH clauses, one for each array. How many rows does JSON_TABLE return, and why?
Show answer
Five rows. Sibling nested paths are combined like a union, so the result has 2 item rows (tag is NULL) plus 3 tag rows (sku is NULL). It is not a cross product, which would give 6 rows.