Sub topic 3
Addressing data with SQL/JSON path expressions
A SQL/JSON path expression is a short string that tells Oracle where to find data inside a JSON document. Every JSON function in this tutorial takes one: JSON_VALUE, JSON_QUERY, JSON_EXISTS, and JSON_TABLE. If you learn the path language once, you can use it in all of them.
This chapter assumes you can read JSON (objects, arrays, scalars) and that you have created a table with a JSON column, as in the previous chapter. The examples use the orders table and the order document inserted there.
The sample document
Every path in this chapter runs against this document:
{
"orderId": 1001,
"customer": {"name": "Ada Lovelace", "city": "London"},
"status": "NEW",
"items": [
{"sku": "A-1", "qty": 2, "price": 9.5},
{"sku": "B-7", "qty": 1, "price": 24}
]
}Anatomy of a path expression
A path expression has three kinds of parts:
- The context item, written
$. It stands for the whole document, or for the item currently being examined. - Steps, which move down into the document. A step is either
.fieldNamefor an object field or[n]for an array element. - An optional filter, written
?( ... ), which keeps only the items that satisfy a condition.
The path $.customer.name starts at the document root, steps into the customer object, then into its name field. The result is Ada Lovelace.
| Path | What it addresses | Result on the sample |
|---|---|---|
| `$` | The whole document | The entire object |
| `$.status` | A top-level field | `"NEW"` |
| `$.customer.city` | A field inside a nested object | `"London"` |
| `$.items` | An array | The whole `items` array |
| `$.items[0]` | One array element, counted from 0 | The first item object |
| `$.items[1].sku` | A field inside one array element | `"B-7"` |
| `$.items[*].sku` | A field in every element | `"A-1"`, `"B-7"` |
Array positions start at 0, not 1. This is the most common slip for people used to SQL, where most counting starts at 1.
Steps in detail
Object steps
The step .name selects the field called name. Field names are case-sensitive, so $.Status does not match status. If a field name contains spaces or other special characters, wrap it in double quotes:
SELECT JSON_VALUE(doc, '$."order status"') FROM orders;You do not need quotes for simple names made of letters, digits, and underscores.
Array steps
Array steps accept several forms:
[0]selects one element.[0, 2]selects elements 0 and 2.[0 to 2]selects a range, inclusive at both ends.[*]selects every element.[last]selects the final element, and[last-1]the one before it.
Wildcards and the descendant step
The wildcard .* selects every field of an object. The path $.customer.* returns both Ada Lovelace and London.
The descendant step ..name searches at any depth. For example, $..sku finds every sku field wherever it appears. This is convenient for exploring an unfamiliar document, but it makes the intent of a query less clear and can be slower on large documents, so prefer explicit paths in production code.
Filter expressions
A filter keeps only the items for which a condition is true. It goes after a step, and inside it the symbol @ stands for the item being tested.
SELECT o.id
FROM orders o
WHERE JSON_EXISTS(o.doc, '$.items[*]?(@.qty > 1)');Read this as: look at each element of items, call it @, and keep it if its qty is greater than 1. JSON_EXISTS returns true when at least one element survives. For the sample order, the first item has qty 2, so the order matches.
Filters support comparison operators (==, !=, <, <=, >, >=), the logical operators && (and), || (or), and ! (not), and the exists condition. Note that equality in a path filter is ==, with two equals signs, not the single = of SQL.
SELECT o.id
FROM orders o
WHERE JSON_EXISTS(o.doc,
'$.items[*]?(@.qty >= 1 && @.price < 10)');Both conditions inside one filter must hold for the same array element. This is different from two separate filters, which can be satisfied by different elements. The next section shows why this matters.
Passing values into a path
Hard-coding literals into a path string invites errors and SQL injection if the value comes from user input. Use a path variable, written with $, and supply it with PASSING:
SELECT o.id
FROM orders o
WHERE JSON_EXISTS(o.doc,
'$.items[*]?(@.sku == $s && @.qty > $q)'
PASSING 'A-1' AS "s", 2 AS "q");With these values, the sample order does not match: the item with sku A-1 has qty 2, and 2 is not greater than 2. Changing $q to 1 makes it match.
SELECT o.id
FROM orders o
WHERE JSON_EXISTS(o.doc,
'$.items[*]?(@.sku == $s && @.qty > $q)'
PASSING 'A-1' AS "s", 1 AS "q");Single-element versus multi-element paths
Some paths can return more than one item. $.items[*].sku returns two. A path that can match several items is a non-singleton path, and the function you use decides what happens:
| Function | Behavior with a multi-item result |
|---|---|
| `JSON_VALUE` | Returns `NULL` by default, because it expects one scalar |
| `JSON_QUERY` | Returns `NULL` unless you add `WITH ARRAY WRAPPER`, which collects the items into an array |
| `JSON_EXISTS` | Returns true if at least one item matches |
| `JSON_TABLE` | Produces one row per item when used as the row path |
To see this, run both of these:
SELECT JSON_VALUE(o.doc, '$.items[*].sku') AS sku_value,
JSON_QUERY(o.doc, '$.items[*].sku' WITH ARRAY WRAPPER) AS sku_array
FROM orders o;The first column is NULL. The second is ["A-1","B-7"]. The next chapter covers these functions and their error handling in full. The point here is that the path alone does not say what you get back. The function's rules do.
Lax and strict mode
A path can start with lax or strict. The default is lax.
- In lax mode, Oracle adapts to small mismatches. If a path expects an array but finds a single object, it treats the object as a one-element array. If a field is missing, the step simply produces no result.
- In strict mode, the path must match the document structure exactly. A missing field or a wrong type is an error.
SELECT JSON_VALUE(o.doc, 'lax $.items.sku') AS lax_result
FROM orders o;Here $.items.sku applies an object step to an array. Lax mode does not fail; it applies the step to each array element, and because two elements match, JSON_VALUE returns NULL for the multi-item result. In strict mode the same path raises an error, because items is an array and not an object.
Lax mode is useful when documents come from different sources and some have a single value where others have an array. Strict mode is better when you want bad data to surface instead of being silently skipped.
Dot notation as shorthand
Oracle also lets you write simple paths as dotted column references, as long as the table has an alias:
SELECT o.doc.customer.name AS customer_name,
o.doc.items[0].sku AS first_sku
FROM orders o;This is shorthand for a path expression with a default JSON_QUERY-style return, and it supports only simple paths without filters. A few points apply:
- The table alias is required.
orders.doc.statuswithout an alias fails. - The result is returned as JSON, so strings keep their JSON form when you serialize them.
- If a path does not exist, the result is
NULL.
Use the functions when you need filters, typed returns, or explicit error handling. Use dot notation for quick reads.
Common errors
- Counting from 1.
$.items[1]is the second item, not the first. - Using
=in a filter. Write@.qty == 2, not@.qty = 2. - Forgetting the
?. A filter is[*]?(...), with the question mark immediately before the parenthesis. - Putting two conditions in separate filters. Use one filter with
&&when both conditions must hold for the same element. - Expecting a scalar from a multi-item path.
JSON_VALUEreturnsNULLrather than the first match. - Quoting. The whole path is a SQL string literal in single quotes. Field names with spaces use double quotes inside it.
- Relying on lax mode to catch mistakes. It will not.
Putting it together
The diagram shows how Oracle evaluates one filtered path from left to right.
Each step takes the items produced by the previous step and moves further into the document. A filter does not change the items; it only decides which ones continue.
Exercise
Using the sample order, what does the path $.items[*]?(@.price > 20).sku return, and why does JSON_VALUE(doc, '$.items[*].sku') on the same document return NULL while JSON_VALUE(doc, '$.items[*]?(@.price > 20).sku') does not?
Show answer
The filtered path returns "B-7". Only the second item has a price above 20 (24), so the filter keeps one element and .sku reads its field. JSON_VALUE expects exactly one scalar. The unfiltered path matches two items (A-1 and B-7), so by default it returns NULL. The filtered path matches exactly one item, so JSON_VALUE can return it.
Exercise
Write a JSON_EXISTS condition that is true only for orders containing an item with sku B-7 and a quantity of at least 1, with both values supplied through PASSING instead of written into the path.
Show answer
JSON_EXISTS(o.doc, '$.items[*]?(@.sku == $s && @.qty >= $q)' PASSING 'B-7' AS "s", 1 AS "q"). Both conditions sit inside one filter, so they must hold for the same array element.