Sub topic 4
Extracting values with JSON_VALUE, JSON_QUERY, and JSON_EXISTS
This chapter assumes you can write SQL/JSON path expressions such as $.customer.name and $.items[0], and that you have the orders table from the earlier chapters on Oracle Database 21c or later. The three functions below are the main tools for reading JSON inside a SQL statement. Most mistakes with them come from not knowing what each function returns when the path does not match.
The working model
Each function evaluates a path against a document and reports the result in a different way.
| Function | Question it answers | Returns | Used in |
|---|---|---|---|
| `JSON_VALUE` | What is the scalar at this path? | One SQL value (string, number, date) | SELECT list, WHERE, ORDER BY, indexes |
| `JSON_QUERY` | What is the object or array at this path? | A JSON fragment | SELECT list |
| `JSON_EXISTS` | Does anything match this path? | True or false | WHERE, CASE conditions |
flowchart TDThe diagram below summarizes how to choose.
JSON_VALUE: one scalar as a SQL value
JSON_VALUE takes a document and a path, and returns the scalar found there. By default the result is a VARCHAR2(4000). Use RETURNING to get a proper SQL type.
SELECT JSON_VALUE(o.doc, '$.customer.name') AS customer_name,
JSON_VALUE(o.doc, '$.orderId' RETURNING NUMBER) AS order_id,
JSON_VALUE(o.doc, '$.items[1].price' RETURNING NUMBER) AS second_price
FROM orders o;For the sample order this returns Ada Lovelace, 1001, and 24.
The RETURNING clause matters in more places than display. Without it, the value is a string, so WHERE JSON_VALUE(doc, '$.orderId') > 9 compares text, and '1001' sorts before '9'. Add RETURNING NUMBER whenever you filter, sort, or do arithmetic on a numeric field. The same applies to dates and timestamps.
What happens when the path does not give a scalar
JSON_VALUE returns NULL in all of these cases by default:
- The path matches nothing, such as
$.customer.email. - The path matches an object or array, such as
$.customeror$.items. - The path matches several values, such as
$.items[*].sku. - The value does not fit the
RETURNINGtype, for example a string of 5000 characters returned asVARCHAR2(4000).
The first case is an empty result. The other three are errors that Oracle hides by default. You control both with ON EMPTY and ON ERROR:
SELECT JSON_VALUE(o.doc, '$.customer.email'
DEFAULT 'n/a' ON EMPTY) AS email,
JSON_VALUE(o.doc, '$.customer'
ERROR ON ERROR) AS bad_path
FROM orders o;The first column returns n/a. The second raises an error because $.customer is an object, not a scalar. During development, ERROR ON ERROR helps you find paths that silently return NULL because of a typo or a wrong assumption about the document shape.
JSON_QUERY: objects, arrays, and fragments
Use JSON_QUERY when the result is a JSON object or array. It returns JSON text (or the JSON type if you ask for it with RETURNING JSON).
SELECT JSON_QUERY(o.doc, '$.customer') AS customer_obj,
JSON_QUERY(o.doc, '$.items') AS all_items,
JSON_QUERY(o.doc, '$.items[0]' PRETTY) AS first_item
FROM orders o;JSON_QUERY rejects scalars by default. JSON_QUERY(doc, '$.status') returns NULL, because "NEW" is not an object or array. You can change this with a wrapper clause, which wraps the matched values in a new array:
SELECT JSON_QUERY(o.doc, '$.items[*].sku' WITH ARRAY WRAPPER) AS skus,
JSON_QUERY(o.doc, '$.status' WITH CONDITIONAL ARRAY WRAPPER) AS status_wrapped,
JSON_QUERY(o.doc, '$.items' WITH CONDITIONAL ARRAY WRAPPER) AS items_unchanged
FROM orders o;The results are:
skusis["A-1","B-7"]. A path with[*]produces several values, andWITH ARRAY WRAPPERcollects them into one array.status_wrappedis["NEW"]. The conditional wrapper wraps the scalar.items_unchangedis the original array. The conditional wrapper only wraps when the result is not already a single object or array.
WITH ARRAY WRAPPER (unconditional) wraps every result, even one that is already an array. That gives you a nested array such as [[{...},{...}]], which is rarely what you want. Prefer the conditional form unless you need a predictable shape.
JSON_EXISTS: filtering on a path
JSON_EXISTS is a condition. It is true when the path returns at least one item. Most useful paths include a filter expression, written as ?( ... ), where @ stands for the current item.
-- Orders with at least one line that has quantity above 1
SELECT o.id
FROM orders o
WHERE JSON_EXISTS(o.doc, '$.items[*]?(@.qty > 1)');
-- Combine conditions with && and ||, and compare strings with double quotes
SELECT o.id
FROM orders o
WHERE JSON_EXISTS(o.doc, '$?(@.status == "NEW" && @.customer.city == "London")');Note the comparison operator inside the path is ==, not =. Inside the filter, string literals use double quotes, which is why the SQL string around the path uses single quotes.
To pass a value from SQL into the path, use PASSING and refer to it with $name. This avoids building path strings by concatenation, which is fragile and a possible injection point.
SELECT o.id
FROM orders o
WHERE JSON_EXISTS(o.doc,
'$.items[*]?(@.sku == $s && @.qty >= $q)'
PASSING 'A-1' AS "s", 2 AS "q");A common mistake is to test a condition with JSON_VALUE and then compare it to NULL. JSON_EXISTS is clearer and cheaper to index. It also tests all array elements at once, which JSON_VALUE cannot do. JSON_EXISTS returns false when the path is invalid, because its default is FALSE ON ERROR. Use ERROR ON ERROR here too when debugging.
Dot notation
Dot notation is a shorter form for simple reads. It requires a table alias, and the column must be a JSON type column or have an IS JSON check constraint.
SELECT o.doc.status,
o.doc.customer.name,
o.doc.items[0].sku
FROM orders o
WHERE o.doc.orderId.number() = 1001;Two differences from JSON_VALUE matter:
- With a
JSONtype column, dot notation returns a value of theJSONtype, not a plain SQL string. Tools usually show a string with its JSON quotes. To get a SQL type, add an item method such as.string(),.number(), or.date(), as in theWHEREclause above, or useJSON_VALUE ... RETURNING. - There are no
ON ERRORorON EMPTYclauses. A missing path returnsNULL, and you cannot ask for an error.
Use dot notation for quick queries and ad hoc reads. Use the functions when you need a specific return type, error handling, wrappers, or an expression that matches an index.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| `JSON_VALUE` returns `NULL` for an object or array | The value is not a scalar | Use `JSON_QUERY` |
| `JSON_QUERY` returns `NULL` for a string or number | Scalar without a wrapper | Add `WITH CONDITIONAL ARRAY WRAPPER` or use `JSON_VALUE` |
| Numeric filter returns wrong rows | Compared as text | Add `RETURNING NUMBER` |
| Path with `[*]` returns `NULL` in `JSON_VALUE` | More than one match | Pick an index such as `[0]`, or use `JSON_TABLE` |
| `ORA-` error on `o.doc.status` | No table alias, or no `IS JSON` constraint on a text column | Add an alias and constraint |
| Index not used | Query expression differs from index definition | Use the same path and `RETURNING` clause as the index |
Exercise
Write a query that returns the SKU of the first line item in each order as a string, and returns only orders where some line item has a price above 20. Which function handles each part?
Show answer
SELECT JSONVALUE(o.doc, '$.items[0].sku') AS firstsku FROM orders o WHERE JSONEXISTS(o.doc, '$.items[*]?(@.price > 20)'); JSONVALUE extracts the scalar SKU, and JSONEXISTS filters on any array element, using a path filter that tests each item. For the sample order, B-7 has price 24, so the order is returned with firstsku A-1.
Exercise
A query uses JSON_QUERY(doc, '$.items[*].qty' WITH ARRAY WRAPPER) and you want to know the result for the sample order. What is it, and what does the query return without the wrapper clause?
Show answer
With the wrapper it returns [2,1], a new array of the matched quantities. Without the wrapper, the path matches two scalar values, which cannot be returned as a single object or array, so the default behavior returns NULL.