Sub topic 1
JSON in Oracle: Why JSON in a relational database
Prerequisites
You should know basic SQL (SELECT, INSERT, WHERE), primary keys, and the JSON format of objects, arrays, and scalar values. The native JSON data type requires Oracle Database 21c or later.
Why store JSON in a relational database
Applications often exchange data as JSON. Oracle Database can store those documents directly, so one database holds both document-shaped data and ordinary tables. Documents suit records whose fields vary from one row to the next. Tables suit data with fixed columns and strict rules. This chapter covers the document side.
Storing documents in JSON columns
Declare a column with the JSON type and insert a document as text:
CREATE TABLE orders (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
doc JSON
);
INSERT INTO orders (doc) VALUES (
'{"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}
]}'
);> Note: Before 21c, store JSON in a VARCHAR2, CLOB, or BLOB column and add CHECK (doc IS JSON) so the database rejects malformed text.
Addressing data with SQL/JSON path expressions
A SQL/JSON path expression names a location inside a document. The symbol $ stands for the whole document.
| Path | Points to |
|---|---|
| `$.status` | the `status` field |
| `$.customer.name` | `name` inside `customer` |
| `$.items[0]` | the first element of `items` |
| `$.items[*]` | every element of `items` |
Extracting values with JSON_VALUE, JSON_QUERY, and JSON_EXISTS
JSON_VALUEreturns one scalar value as a SQL type.JSON_QUERYreturns an object or array as a JSON fragment.JSON_EXISTSreturns true when a path matches. Use it in a WHERE clause.- Dot notation, such as
o.doc.status, reads a simple field. It requires a table alias.
SELECT JSON_VALUE(o.doc, '$.customer.name') AS customer_name,
JSON_QUERY(o.doc, '$.items[0]') AS first_item,
o.doc.status AS status
FROM orders o
WHERE JSON_EXISTS(o.doc, '$.items[*]?(@.qty > 1)');> Warning: JSON_VALUE returns NULL when the path points to an object or array. Use JSON_QUERY for those.
Exercise
Which function returns the items array as a JSON fragment, and which returns only a scalar such as the customer's name?
Show answer
JSONQUERY returns the items array as a JSON fragment. JSONVALUE returns a scalar such as the customer's name.