Sub topic 2
Turning JSON into rows with JSON_TABLE
This chapter assumes you know SQL joins and GROUP BY, you have Oracle Database 21c or later, and you have an orders table whose doc column is a JSON column, as created earlier in the tutorial.
Turning JSON into rows with JSON_TABLE
JSON_TABLE maps values in a JSON document to relational columns. Used in the FROM clause, it produces one row per array element and joins each row to its parent.
SELECT o.id, jt.sku, jt.qty, jt.price
FROM orders o,
JSON_TABLE(o.doc, '$.items[*]'
COLUMNS (
sku VARCHAR2(20) PATH '$.sku',
qty NUMBER PATH '$.qty',
price NUMBER PATH '$.price'
)) jt;Flattening nested arrays with NESTED PATH
When an array sits inside another structure, NESTED PATH extracts its elements while repeating the parent columns on each row. FOR ORDINALITY numbers the elements within each array.
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;Generating JSON with JSON_OBJECT and JSON_ARRAYAGG
JSON_OBJECT builds a JSON object from key-value pairs. JSON_ARRAYAGG collects grouped values into a JSON array.
SELECT JSON_OBJECT(
'orderId' VALUE o.id,
'items' VALUE JSON_ARRAYAGG(
JSON_OBJECT('sku' VALUE jt.sku, 'qty' VALUE jt.qty)
)
) AS doc
FROM orders o,
JSON_TABLE(o.doc, '$.items[*]'
COLUMNS (
sku VARCHAR2(20) PATH '$.sku',
qty NUMBER PATH '$.qty'
)) jt
GROUP BY o.id;Changing documents with JSON_TRANSFORM and JSON_MERGEPATCH
JSON_TRANSFORM applies named operations, such as SET and REMOVE, to specific paths. JSON_MERGEPATCH merges a patch document into the target, and a null value in the patch deletes that key.
UPDATE orders o
SET o.doc = JSON_TRANSFORM(o.doc,
SET '$.status' = 'SHIPPED',
REMOVE '$.customer.city')
WHERE JSON_VALUE(o.doc, '$.orderId' RETURNING NUMBER) = 1001;
UPDATE orders
SET doc = JSON_MERGEPATCH(doc, '{"status": "DELIVERED", "customer": {"city": null}}')
WHERE id = 1;Indexing JSON for performance
A function-based index on a JSON_VALUE expression speeds up equality lookups on one field. A JSON search index supports ad hoc queries across the whole document.
CREATE INDEX orders_customer_ix
ON orders (JSON_VALUE(doc, '$.customer.name' RETURNING VARCHAR2(100)));
CREATE SEARCH INDEX orders_doc_si ON orders (doc) FOR JSON;Exercise
Exercise
Write a query that returns each order's id and the sku of every item whose qty is greater than 1.
Show answer
SELECT o.id, jt.sku FROM orders o, JSON_TABLE(o.doc, '$.items[*]' COLUMNS (sku VARCHAR2(20) PATH '$.sku', qty NUMBER PATH '$.qty')) jt WHERE jt.qty > 1;