Sub topic 1
Why JSON in a relational database
JSON is the usual format for data that arrives from web APIs, mobile apps, and event streams. Relational tables are still the best-understood way to store data that must stay consistent. Oracle Database lets you keep both in one engine and query them with one language, SQL. This chapter explains why that matters, how Oracle supports JSON, and what you give up when you choose each model. Later chapters cover the syntax in detail.
Prerequisites
This chapter assumes you already have the following:
- Basic SQL: SELECT, INSERT, UPDATE, joins, and GROUP BY.
- Relational design: primary keys, foreign keys, and why tables are normalized.
- The JSON format: objects, arrays, and scalar values (strings, numbers, booleans, null).
- Access to Oracle Database 21c or later to run the native
JSONtype examples. Duality views, introduced at the end of this chapter, need 23ai.
The problem JSON solves
A relational table fixes its shape up front. Every row has the same columns, and a change to the shape needs an ALTER TABLE. That is a strength when the data is regular, such as invoices, accounts, or inventory counts.
Three situations strain that model:
- Variable attributes. A product catalog might hold shoes with a
sizeand laptops with acpuandram. A column for every possible attribute leaves most cells empty. - Nested data that travels as a unit. An order with its customer and line items is one document in an application. Normalized, it is three or more tables that must be joined and reassembled on every read.
- Data you do not control. Payloads from a third-party API, log events, and device telemetry change shape without notice. Rejecting a payload because a new field appeared is often the wrong behavior.
Document databases answer these with schema-flexible storage. Their cost is that cross-document consistency, joins, and transactions across documents are weaker or left to the application. Oracle's approach is to add JSON to the relational engine, so a single database holds both shapes and a single transaction can touch both.
How Oracle supports JSON
Oracle's JSON support was added in layers. Knowing the layers explains why you will see different syntax in different code bases.
| Version | What was added |
|---|---|
| 12.1.0.2 | JSON stored in `VARCHAR2`, `CLOB`, or `BLOB` columns, validated with the `IS JSON` condition. SQL/JSON functions such as `JSON_VALUE`, `JSON_QUERY`, `JSON_EXISTS`, and `JSON_TABLE`. |
| 12.2 and 18c | Generation functions such as `JSON_OBJECT` and `JSON_ARRAYAGG`, plus JSON search indexes. |
| 19c | `JSON_MERGEPATCH` for patch-style updates. |
| 21c | The native `JSON` data type, stored in a binary format, and `JSON_TRANSFORM`. |
| 23ai | JSON-relational duality views. |
Two ideas run through all of these.
- JSON is data inside a column, not a separate store. A JSON value sits in a column next to ordinary columns, protected by the same transactions, backups, security, and indexes as the rest of the row.
- SQL reaches into the document. Functions take a path expression, a small language for pointing at a field or array element, and return SQL values. Once a value is a SQL value, you can filter, join, group, and sort it like any other.
Native type versus constrained text
Before 21c, JSON lived in text columns. You made the column safe by adding a check constraint:
CREATE TABLE events_text (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload VARCHAR2(4000)
CONSTRAINT events_payload_json CHECK (payload IS JSON)
);
INSERT INTO events_text (payload)
VALUES ('{"type": "login", "user": "ada"}');Without the constraint, the column accepts any string, and a malformed document is found only when a query fails on it. With the constraint, an insert of '{"type": ' is rejected at write time with ORA-02290: check constraint ... violated.
The native type moves that check into the column itself. In the native type, the database parses the text once, on insert, and stores a binary representation. Queries then read the binary form and skip re-parsing. An insert of invalid text into a JSON column fails with a JSON syntax error (ORA-40441), and no separate constraint is needed.
CREATE TABLE customer (
customer_id NUMBER PRIMARY KEY,
name VARCHAR2(100) NOT NULL,
preferences JSON
);
INSERT INTO customer (customer_id, name, preferences)
VALUES (1, 'Ada Lovelace', '{"theme": "dark", "newsletter": true}');
SELECT c.name,
JSON_VALUE(c.preferences, '$.theme') AS theme
FROM customer c
WHERE c.customer_id = 1;This table shows the hybrid pattern that most real designs use. The stable, important attributes (customer_id, name) are ordinary columns with a primary key and NOT NULL. The loosely structured part (preferences) is a JSON column. The JSON_VALUE function in the query reads one field from the document and returns it as a SQL value. Chapter 4 covers that function and its siblings.
For new work on 21c or later, prefer the native JSON type. Use constrained VARCHAR2, CLOB, or BLOB columns when you must run on 19c or earlier, or when other tools require the data in a text column.
What you gain and what you give up
Storing a document in a JSON column is not free of trade-offs. These are the ones that decide most designs.
| Concern | JSON column | Normalized tables |
|---|---|---|
| Changing the shape | No DDL. New fields appear when the application writes them. | `ALTER TABLE`, and often a data migration. |
| Reading a whole aggregate | One row read returns the whole order. | Joins across several tables. |
| Constraints | Only what you add: `IS JSON`, or a JSON schema validation. No foreign keys into the document. | Primary keys, foreign keys, `NOT NULL`, and check constraints. |
| Updating one field | Rewrites part or all of the document, depending on the operation. | Updates one column in one row. |
| Reporting across documents | Needs path expressions or `JSON_TABLE` to turn fields into columns. | Plain SQL. |
| Data duplication | A customer's name is repeated in every order document. | Stored once and referenced. |
The duplication row is the one that surprises people. If a customer changes their name, a relational design updates one row. A design that copied the name into thousands of order documents must update every one of them, or accept that old orders keep the old name. Sometimes keeping the old name is exactly right, because an invoice should record what was true at the time. Decide this deliberately instead of by accident.
Common errors at this stage
These mistakes appear often when people first mix JSON and SQL.
- Using a JSON column as a dumping ground. If every row has the same fields and you filter on them constantly, they belong in columns. A JSON column hides them from constraints and from the optimizer's column statistics.
- Forgetting the constraint on text columns. A
CLOBwithoutIS JSONis just text. Path functions on it raise errors at query time, or silently return nothing depending on the error clause, instead of failing at insert time. - Expecting JSON keys to be case-insensitive. Keys in the document and in path expressions are case-sensitive.
$.Statusdoes not match"status". - Treating the result type as a string.
JSON_VALUEreturns aVARCHAR2by default, so a number compared against another number can behave as a string comparison unless you ask for the right return type. Chapter 4 coversRETURNING. - Assuming duplicated data stays in sync. Copies of a value inside documents are independent. Nothing updates them when the original changes.
Where duality views fit
The choice above looks like a fork: documents with flexibility, or tables with integrity. JSON-relational duality views (23ai) are Oracle's attempt to remove the fork. The data is stored once, in normalized tables. A view presents it as an updatable JSON document, and applications can read and write documents while the database maintains the rows underneath. The same rows stay directly queryable with plain SQL. Chapters 10 through 13 build one from scratch. For now, remember that duality views make the access style a choice that is separate from the storage style.
Roadmap
The remaining chapters follow the order of the concept graph:
- Create JSON columns and constrain text columns with
IS JSON. - Address data with path expressions and extract it with
JSON_VALUE,JSON_QUERY,JSON_EXISTS, and dot notation. - Turn arrays into rows with
JSON_TABLEandNESTED PATH. - Generate JSON from relational data with
JSON_OBJECTandJSON_ARRAYAGG. - Update documents with
JSON_TRANSFORMandJSON_MERGEPATCH, and index them. - Define and use duality views, including ETags and updatability annotations.
- Choose among the three models for a given workload.
Exercise
A table stores support tickets. Every ticket has an ID, a creation time, a status that is always one of three values, and a customer ID that must exist in a customer table. Tickets also carry a set of optional, team-specific fields that differ by team and change often. Which parts would you put in ordinary columns, which in a JSON column, and why?
Show answer
Put the ID, creation time, status, and customer ID in ordinary columns. They are present on every row, and they need a primary key, a check constraint for the three status values, and a foreign key to the customer table, which a JSON document cannot provide. Put the team-specific optional fields in a JSON column (native JSON on 21c or later). They vary by team and change often, so a JSON column lets them change without ALTER TABLE or sparse columns. This hybrid design keeps integrity where it matters and flexibility where it is needed.
Exercise
You are on Oracle Database 19c and want to store JSON in a CLOB column. What must you add to the column definition so malformed documents are rejected at insert time, and which error do you get when one is inserted?
Show answer
Add a check constraint using the IS JSON condition, for example CHECK (payload IS JSON). Inserting malformed text then fails with ORA-02290: check constraint ... violated. Without the constraint, the column accepts any text and errors appear only when a query tries to read the bad value.