Sub topic 5
Turning JSON into rows with JSON_TABLE
This chapter assumes you know basic SQL joins and aggregation. It also assumes you can read a SQL/JSON path such as $.items[*].sku, and that you have the orders table from the earlier chapters (a JSON column named doc, Oracle Database 21c or later). JSON_TABLE also works on VARCHAR2, CLOB, and BLOB columns that have an IS JSON check constraint.
Why JSON_TABLE exists
JSON_VALUE returns one scalar and JSON_QUERY returns one fragment. Each call reads a single location, so extracting many fields means calling the function many times, and an array can't be turned into rows this way.
JSON_TABLE fixes both problems. You give it a document, a path that selects zero or more JSON items, and a list of columns. Oracle produces one relational row for each selected item. You can then use WHERE, GROUP BY, joins, and analytic functions on the result as if it were an ordinary table.
The working model
A JSON_TABLE call has two kinds of paths:
- The row path is the second argument. It picks the items that become rows.
'$.items[*]'yields one row per array element.'$'yields exactly one row for the whole document. - Each column path is evaluated relative to one item chosen by the row path. In
PATH '$.sku', the$means the current array element, not the document root.
A first query
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;For the order inserted earlier, this returns two rows:
| ID | SKU | QTY | PRICE |
|---|---|---|---|
| 1 | A-1 | 2 | 9.5 |
| 1 | B-7 | 1 | 24 |
The JSON_TABLE on the right refers to o.doc from the table on the left. Oracle evaluates it once per orders row, so this is a correlated (lateral) join even though the SQL uses a comma. The alias jt is required if you want to reference the columns.
Because the output is relational, aggregation works directly:
SELECT o.id, SUM(jt.qty * jt.price) AS order_total
FROM orders o,
JSON_TABLE(o.doc, '$.items[*]'
COLUMNS (
qty NUMBER PATH '$.qty',
price NUMBER PATH '$.price'
)) jt
GROUP BY o.id;For order 1001 the total is 2 × 9.5 + 1 × 24 = 43.
Column types
Every column has a name, usually a SQL data type, and a way to find its value. The common forms are below.
| Column form | What it returns |
|---|---|
| `col VARCHAR2(n) PATH '$.x'` | A scalar converted to the SQL type. Works for `NUMBER`, `DATE`, `TIMESTAMP`, and others. |
| `col VARCHAR2(n) FORMAT JSON PATH '$.x'` | An object or array as JSON text, like `JSON_QUERY`. |
| `col VARCHAR2(5) EXISTS PATH '$.x'` | `'true'` or `'false'` depending on whether the path matches anything, like `JSON_EXISTS`. |
| `col FOR ORDINALITY` | A sequence number, 1 for the first item selected by the row path, 2 for the next, and so on. |
| `NESTED PATH '$.x[*]' COLUMNS (...)` | Rows from an inner array, repeated alongside the parent columns. The next chapter covers this. |
Here is a query that uses three of these forms:
SELECT jt.*
FROM orders o,
JSON_TABLE(o.doc, '$.items[*]'
COLUMNS (
line_no FOR ORDINALITY,
sku VARCHAR2(20) PATH '$.sku',
has_discount VARCHAR2(5) EXISTS PATH '$.discount'
)) jt;If you just need all matching fields as a single column of JSON text, such as the whole customer object, use FORMAT JSON:
SELECT jt.customer_json
FROM orders o,
JSON_TABLE(o.doc, '$'
COLUMNS (
customer_json VARCHAR2(200) FORMAT JSON PATH '$.customer'
)) jt;Missing values and bad values
Real documents are irregular. Some items lack a field, and some have the wrong type. JSON_TABLE has per-column clauses for both cases, using the same ON EMPTY and ON ERROR vocabulary as JSON_VALUE.
- A path that matches nothing is "empty". The default is
NULL ON EMPTY. You can writeDEFAULT 1 ON EMPTYorERROR ON EMPTY. - A value that can't be converted is an "error". Examples are text such as
"n/a"in aNUMBERcolumn, a value longer than the declaredVARCHAR2(n), or an array where a scalar was expected. The default isNULL ON ERROR. You can writeERROR ON ERRORorDEFAULT 0 ON ERROR.
SELECT jt.*
FROM orders o,
JSON_TABLE(o.doc, '$.items[*]'
COLUMNS (
sku VARCHAR2(20) PATH '$.sku',
qty NUMBER PATH '$.qty' DEFAULT 1 ON EMPTY,
price NUMBER PATH '$.price' ERROR ON ERROR
)) jt;Here an item with no qty is treated as quantity 1. An item whose price is not numeric makes the whole statement fail with an error instead of silently producing NULL.
Keeping orders that have no items
The comma join in the examples behaves like an inner join. An order whose items array is empty or missing produces no JSON_TABLE rows, so that order vanishes from the result. To keep it, use OUTER APPLY, which is the lateral equivalent of a left join:
SELECT o.id, jt.sku, jt.qty
FROM orders o
OUTER APPLY JSON_TABLE(o.doc, '$.items[*]'
COLUMNS (
sku VARCHAR2(20) PATH '$.sku',
qty NUMBER PATH '$.qty'
)) jt;Orders with no items now appear once, with NULL in sku and qty. CROSS APPLY is the explicit spelling of the inner-join behavior.
Wrapping JSON_TABLE in a view
Once a JSON_TABLE query is correct, you can put it behind a view. Analysts and reporting tools then see an ordinary relational shape and never need to know about JSON paths.
CREATE OR REPLACE VIEW order_lines_v AS
SELECT o.id AS order_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;
SELECT sku, SUM(qty) AS units_sold
FROM order_lines_v
GROUP BY sku;This view is read-only. To change a document you still update the doc column, using the techniques from the chapter on JSON_TRANSFORM.
Common errors and gotchas
- Wrong row path. If the row path matches nothing, the query returns no rows for that document and no error. In strict mode a missing field is an error, but the default is lax, so check the path first when results are empty.
- Absolute paths in columns. Column paths are relative to the row item. Writing
PATH '$.items[0].sku'inside a$.items[*]row path looks inside each element for anitemsfield, which usually doesn't exist and returnsNULL. - Scalar versus fragment. A
PATHcolumn pointing at an object or array returnsNULLby default, because it is not a scalar. AddFORMAT JSONto get the fragment. - Missing alias. Without an alias on
JSON_TABLE, you can't qualify its columns, andSELECT *can produce name clashes with the base table. - Number precision. A
NUMBERcolumn with no precision keeps the JSON value as is. DeclaringNUMBER(5,2)rounds or rejects values that don't fit, which may be what you want or may hide data. - Mixed types. If
qtyis sometimes a number and sometimes a string such as"2", aNUMBERcolumn converts the string in lax mode. A string such as"two"becomesNULL(or an error withERROR ON ERROR).
Exercise
Write a query that lists each order's id and the number of line items it contains, as line_count. Orders with no items array must still appear, with a count of 0. Which join form do you need, and which expression do you count?
Show answer
Use OUTER APPLY and count a column from the JSONTABLE, not COUNT(*). For example: SELECT o.id, COUNT(jt.sku) AS linecount FROM orders o OUTER APPLY JSONTABLE(o.doc, '$.items[*]' COLUMNS (sku VARCHAR2(20) PATH '$.sku')) jt GROUP BY o.id. OUTER APPLY keeps orders with no rows from JSONTABLE and gives them NULL in jt.sku. COUNT(jt.sku) ignores NULLs, so those orders get 0, while COUNT(*) would count the padded row and return 1. (This assumes every real item has a sku; if some items lack one, use FOR ORDINALITY and count that column instead.)
Exercise
A query uses price NUMBER PATH '$.price' inside JSON_TABLE(o.doc, '$.items[*]' ...). One item contains "price": "free". What does that row show for price, and how do you make the query report the problem instead?
Show answer
The default is NULL ON ERROR, so the row appears with price NULL and no message. Add ERROR ON ERROR to the column (price NUMBER PATH '$.price' ERROR ON ERROR) and the statement fails with an error. Alternatively, use DEFAULT 0 ON ERROR if a fallback value is acceptable.