Sub topic 10
The document versus relational dilemma
This chapter assumes you can write SQL joins and design tables with primary and foreign keys. It also assumes you have read the earlier chapters on JSON columns, JSON_TABLE, and JSON_TRANSFORM. No new syntax appears here. The chapter explains the design problem that JSON-relational duality views (Oracle Database 23ai) were built to solve, so the next chapter makes sense.
Two ways to model the same order
An order has a customer, a status, and a list of line items. You can store it in two ways.
In the document model, the whole order is one JSON value. The application reads and writes it as a unit. This is the orders table you built earlier:
CREATE TABLE orders (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
doc JSON
);In the relational model, the order is split across normalized tables. Each fact is stored once, and foreign keys connect the tables:
CREATE TABLE customer (
customer_id NUMBER PRIMARY KEY,
name VARCHAR2(100) NOT NULL,
city VARCHAR2(100)
);
CREATE TABLE purchase_order (
order_id NUMBER PRIMARY KEY,
customer_id NUMBER NOT NULL REFERENCES customer (customer_id),
status VARCHAR2(20) NOT NULL
);
CREATE TABLE order_item (
order_id NUMBER NOT NULL REFERENCES purchase_order (order_id),
line_no NUMBER NOT NULL,
sku VARCHAR2(20) NOT NULL,
qty NUMBER NOT NULL,
price NUMBER NOT NULL,
PRIMARY KEY (order_id, line_no)
);The table is named purchase_order because ORDER is a reserved word in SQL.
Both models hold the same information. They differ in who does the work of assembling it, and in what the database can guarantee.
What the document model does well
One read returns the whole object. To show an order page, you fetch one row and get the customer, status, and items together. No join is needed.
SELECT o.doc FROM orders o WHERE o.id = 1;One write stores the whole object. The application builds a JSON value and inserts it. The code that maps objects to rows disappears, and so does the mismatch between how developers think (nested objects) and how the tables are laid out (flat rows).
The shape can change without DDL. If a new kind of order needs a giftMessage field, you add it to those documents. No ALTER TABLE is needed, and old documents stay valid.
The data model matches the API. Services that exchange JSON over REST can store exactly what they send and receive.
Where the document model hurts
Duplicated facts. The customer's name and city are copied into every order. Suppose Ada Lovelace moves. You must find every document that mentions her and rewrite it:
UPDATE orders o
SET o.doc = JSON_TRANSFORM(o.doc, SET '$.customer.city' = 'Cambridge')
WHERE JSON_VALUE(o.doc, '$.customer.name') = 'Ada Lovelace';This statement has two problems. It identifies the customer by name, so two different people called Ada Lovelace are both changed. It also touches every order she ever placed, and each touched document is rewritten in full. If one application forgets to update the copy it holds, the data becomes inconsistent. Nothing in the database prevents that.
Few integrity guarantees. Nothing stops qty from being a string, or customer from being missing. You can add an IS JSON check or a JSON schema check, but you cannot declare a foreign key from a path inside a document to another table.
Awkward cross-document queries. Answering "total quantity sold per SKU" means unnesting every document with JSON_TABLE. This works, and indexes can help, but the optimizer has fewer statistics than it has for ordinary columns. Large documents also make every small change expensive, because a one-field update rewrites the whole value.
The shape is fixed to one use. An order-centric document is convenient for the order page. A warehouse report wants one row per item, and a customer service tool wants one row per customer. Each of those views fights the shape you chose.
What the relational model does well
Each fact lives in one place. Updating the customer's city is one row:
UPDATE customer SET city = 'Cambridge' WHERE customer_id = 1;Every order sees the change immediately.
The database enforces the rules. Primary keys, foreign keys, NOT NULL, and column types are checked on every write, regardless of which application connects.
Many access patterns work from one design. Because the data is not shaped for a single screen, you can join and aggregate it in whatever way a new report requires. The optimizer has accurate statistics on each column.
Fine-grained concurrency. Two sessions updating different rows do not conflict. Two sessions editing different fields of the same JSON document do conflict, because the document is the unit that gets written.
Where the relational model hurts
Reassembling objects takes work. To build one order page, you join three tables and group the result back into a nested structure:
SELECT o.order_id, c.name, o.status, i.line_no, i.sku, i.qty, i.price
FROM purchase_order o
JOIN customer c ON c.customer_id = o.customer_id
JOIN order_item i ON i.order_id = o.order_id
WHERE o.order_id = 1001
ORDER BY i.line_no;The result is flat rows with the order and customer values repeated on each line. The application must turn them back into an object. Writing is harder: one new order is an INSERT into purchase_order plus one INSERT per item, all in one transaction.
Object-relational mapping layers add cost. Many teams add an ORM to hide this work. ORMs introduce their own problems, such as extra queries per object and generated SQL that is hard to tune.
Schema changes need coordination. A new attribute means a DDL change and often a deployment across several services.
Mismatch with JSON-speaking clients. Mobile apps, front ends, and document-oriented drivers want JSON. Someone has to convert it at the boundary, in every application.
A comparison
| Concern | Document model (JSON column) | Relational model (normalized tables) |
|---|---|---|
| Read one whole object | One row, no joins | Joins plus reshaping |
| Write one whole object | One insert | Several inserts in one transaction |
| Change a shared fact (customer city) | Rewrite every document that embeds it | Update one row |
| Integrity rules | Mostly in the application | Declared in the database |
| Schema evolution | Add fields freely | DDL change |
| New query shapes | Possible, often costly | Natural |
| Concurrent edits to one object | Whole document is the unit | Row-level |
The usual workarounds
Teams commonly choose one model and bolt on features from the other.
- Documents plus extra structure. Keep JSON documents, but copy key fields into relational columns or indexes so reports can query them. This duplicates data, and the copies can drift.
- Relational tables plus JSON generation. Keep normalized tables and build JSON on the way out with
JSON_OBJECTandJSON_ARRAYAGG. Reads become easy, but writes still require code that splits a document back into rows. - Both, kept in sync. Store documents for the application and tables for reporting, and sync them with triggers or jobs. This is the most flexible and the most fragile option, and it needs careful testing.
What the dilemma suggests
The two models are good at different things, and the problems come from forcing one data store to pick a single representation. The ideal would be:
- Store the data once, in normalized tables, so facts are not duplicated and constraints apply.
- Let applications read and write whole nested objects as JSON, with no mapping layer.
- Let reports and other applications use SQL on the same tables, at the same time.
JSON-relational duality views, covered next, are Oracle's way of offering this. A duality view is defined over ordinary tables and presents each row tree as an updatable JSON document. A single insert of a document writes rows into several tables. The tables remain the single source of truth, and you can still query them directly.
Deciding where you stand today
Before the next chapter, check which pain you feel most. These questions help.
- Is the same fact (a customer, a product price) embedded in many documents? That pushes you toward relational storage.
- Is the data written once and read whole, with a varying shape? That favors documents.
- Do several teams or tools need to query the data in different ways? That favors relational tables, or a duality view over them.
- Do clients exchange JSON and need to update parts of it? That is the case duality views handle best.
Exercise
An orders table stores each order as a JSON document that embeds the customer's name and city. A customer changes address. Give two specific problems with fixing this using JSON_TRANSFORM and a WHERE clause on the customer name.
Show answer
First, the name is not a key, so two different customers with the same name are both changed. Second, every document that embeds the customer must be found and rewritten in full, and any copy that is missed (or any application holding its own copy) leaves the data inconsistent. In a normalized customer table this is one row update on customer_id.
Exercise
Name two things the relational model gives you that a plain JSON column does not, and one cost it adds for an application that works with whole orders.
Show answer
It gives you declared integrity (primary keys, foreign keys, NOT NULL, typed columns) enforced by the database, and a single stored copy of each fact so one update is seen everywhere. It also supports many query shapes through joins and aggregates. The cost is that reading or writing one whole order means joining or inserting into several tables and converting between flat rows and a nested object, either by hand or through an ORM.
Exercise
A table stores API responses exactly as received. They are written once, shown as a whole, and never edited. Is a JSON column or normalized tables the better fit, and why?
Show answer
A JSON column. The data is immutable and read as a unit, so duplication and update anomalies do not arise. Storing it as-is also avoids a mapping step and tolerates changes in the response shape without DDL.