Sub topic 2
Storing documents in JSON columns
This chapter covers how to store JSON documents in a table, and which column type to choose. It assumes you can write basic SQL (CREATE TABLE, INSERT, SELECT) and know what JSON objects, arrays, and scalar values are. The native JSON type needs Oracle Database 21c or later. The IS JSON constraint works on older releases (12.1.0.2 and later).
Two ways to store JSON
Oracle gives you two options for a column that holds documents:
- The native
JSONdata type (21c and later). Oracle parses the text you insert and stores it in a binary format called OSON. - A
VARCHAR2,CLOB, orBLOBcolumn with anIS JSONcheck constraint. The column holds the original text, and the constraint rejects anything that is not valid JSON.
| Aspect | `JSON` type | `VARCHAR2` / `CLOB` / `BLOB` with `IS JSON` |
|---|---|---|
| Minimum release | 21c | 12.1.0.2 |
| Stored form | Binary (OSON) | Text, exactly as inserted |
| Validation | Always, at insert time | Only if you add the constraint |
| Query speed | Faster: no text parsing per query | Slower: text is parsed on each access |
| Original whitespace and key order | Not preserved | Preserved |
| Extra scalar types (dates, timestamps, binary) | Supported | Not available in text |
| Size | Up to 32 MB per document | `VARCHAR2` up to 4000 bytes (32767 with extended strings), `CLOB` and `BLOB` much larger |
Use the JSON type for new work on 21c or later. Use a constrained text column when you must support older releases or must keep the exact original text, for example for signatures or audit records.
Correction: the diagram goes in the required fence format below.
Creating a table with a JSON column
The JSON type is declared like any other type. This table is the one used in the rest of the tutorial.
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}
]}'
);The string literal is not stored as text. Oracle converts it to the JSON type during the insert. If the text is not valid JSON, the insert fails with a JSON syntax error (ORA-40441) and no row is written.
A few details follow from the binary storage:
- Whitespace and the order of fields inside an object are not preserved. Do not write code that depends on field order.
- Numbers keep their exact decimal value.
9.5stays9.5. - Each value has a JSON scalar type: string, number, boolean, null, or one of the extra types Oracle adds (date, timestamp, binary, and others). These extra types cannot be written in plain JSON text, but they can appear in documents that SQL generates.
- A SQL
NULLin the column means "no document". A document whose content is the JSON valuenullis a different thing.
Literals and size
A SQL string literal is limited to 4000 bytes in standard mode. For larger documents, bind a CLOB, BLOB, or JSON value from your driver instead of building a literal.
Reading a JSON column back as text
Tools show a JSON column as text, but the value is binary. When you need text, for example to send it to an application or to read it, convert it explicitly with JSON_SERIALIZE.
SELECT JSON_SERIALIZE(doc PRETTY) AS pretty_doc
FROM orders
WHERE id = 1;
SELECT JSON_SERIALIZE(doc RETURNING CLOB) AS doc_text
FROM orders;PRETTY adds indentation. RETURNING sets the output type, which defaults to VARCHAR2. If the document is larger than the target type allows, the call raises an error unless you ask for CLOB.
Storing JSON in a text column with IS JSON
On releases before 21c, or when you must keep the exact text, use a text column and add a check constraint.
CREATE TABLE orders_legacy (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
doc BLOB,
CONSTRAINT orders_legacy_doc_json CHECK (doc IS JSON)
);
INSERT INTO orders_legacy (doc)
VALUES (UTL_RAW.CAST_TO_RAW('{"orderId": 2001, "status": "NEW"}'));Notes on this approach:
- Prefer
BLOB. It avoids character-set conversion and is the most compact.CLOBstores text in a form that may take about twice the space of the same text inBLOB, depending on the database character set. - Without the constraint, the column accepts anything. JSON functions will then fail or return nothing on bad rows. Always add the
IS JSONcheck. - A violation raises ORA-02290 (check constraint violated), as for any other check constraint.
Strict and lax syntax
IS JSON is lax by default. It accepts some non-standard input, such as unquoted field names and single-quoted strings. Add STRICT to accept only standard JSON. Add WITH UNIQUE KEYS to reject objects that repeat a field name.
CREATE TABLE audit_log (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
doc CLOB,
CONSTRAINT audit_log_doc_json
CHECK (doc IS JSON STRICT WITH UNIQUE KEYS)
);
-- Fails with ORA-02290: the field "a" appears twice
INSERT INTO audit_log (doc) VALUES ('{"a": 1, "a": 2}');Duplicate field names are legal in some parsers, and which value wins varies between them. If your documents come from several systems, WITH UNIQUE KEYS avoids surprises later.
The JSON type does not need these clauses, because its parser always enforces valid input.
Testing whether text is JSON
IS JSON is also a condition you can use in a query. It is useful when you inherit a column that was never constrained.
CREATE TABLE raw_events (
id NUMBER PRIMARY KEY,
payload VARCHAR2(4000)
);
INSERT INTO raw_events VALUES (1, '{"type": "login", "user": "ada"}');
INSERT INTO raw_events VALUES (2, 'not json at all');
-- Find rows that are not valid JSON
SELECT id FROM raw_events WHERE payload IS NOT JSON;
-- Use only the valid rows
SELECT JSON_VALUE(payload, '$.user') AS usr
FROM raw_events
WHERE payload IS JSON;Once you have cleaned up the bad rows, add the check constraint with ALTER TABLE raw_events ADD CONSTRAINT ... CHECK (payload IS JSON). Oracle validates the existing rows when it adds the constraint, so the statement fails if any are invalid.
Moving from text to the JSON type
To migrate a text column to the native type, add a JSON column, copy the data with the JSON constructor, and check the result before dropping the old column.
ALTER TABLE orders_legacy ADD (doc_json JSON);
UPDATE orders_legacy
SET doc_json = JSON(doc);
SELECT COUNT(*) AS migrated
FROM orders_legacy
WHERE doc_json IS NOT NULL;The JSON constructor accepts character and binary input and raises an error on invalid text, so the update is a validation step as well.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| ORA-40441 JSON syntax error on insert into a `JSON` column | The text is not valid JSON, for example a trailing comma or an unquoted string | Fix the document and validate it before sending |
| ORA-02290 on insert into a text column | The `IS JSON` constraint rejected the value (lax or strict rules, or duplicate keys) | Fix the document, or loosen the constraint deliberately |
| Output cut off or an error from `JSON_SERIALIZE` | The default `VARCHAR2` return type is too small | Add `RETURNING CLOB` |
| Field order differs from what you inserted | Binary storage does not keep order | Do not rely on order, or keep a text column if you need it |
| Literal too long | Standard string literals are limited to 4000 bytes | Bind a `CLOB`, `BLOB`, or `JSON` value instead |
Exercise
You are on Oracle Database 19c and must keep a nightly export of customer documents byte for byte, including whitespace, for audits. Which column definition do you use, and why not the JSON type?
Show answer
Use a BLOB column with a CHECK (doc IS JSON) constraint, adding STRICT WITH UNIQUE KEYS if the exports must be standard JSON with no repeated field names. The JSON type is not available before 21c, and even where it is, it stores a binary form that does not preserve whitespace or field order, so the exact original text could not be reproduced.
Exercise
A table has a column payload VARCHAR2(4000) with no constraint. How do you list the rows that are not valid JSON, and how do you prevent new bad rows afterwards?
Show answer
Run SELECT id FROM rawevents WHERE payload IS NOT JSON; to list the bad rows. Fix or delete them, then run ALTER TABLE rawevents ADD CONSTRAINT payload_json CHECK (payload IS JSON); so Oracle rejects invalid values from then on. The ALTER fails if any existing row is still invalid.
Exercise
What does JSON_SERIALIZE(doc RETURNING CLOB PRETTY) do, and when do you need it for a JSON column?
Show answer
It converts the binary JSON value to indented text returned as a CLOB. You need it whenever you want the document as text, for example to display it or send it to an application, and the CLOB return type avoids length errors on large documents.