Sub topic 14
Choosing the right model
This chapter assumes you have worked through the earlier chapters. You should know the native JSON type, JSON_VALUE, JSON_TABLE, JSON_TRANSFORM, JSON indexes, and duality views. Here you will turn that toolbox into decisions. Oracle Database gives you four ways to hold the same business data, and the right one depends on how the data is written, read, and changed.
The four options
- Relational tables hold each fact in typed columns, with keys and constraints. Joins combine them.
- A JSON column holds a whole document in one column, usually in a table that also has ordinary columns.
- A hybrid table is a relational table with a JSON column for the variable part of each row.
- A duality view (Oracle Database 23ai) stores the data in normalized tables and exposes it as updatable JSON documents.
The options are not exclusive. One schema often uses all four for different parts of the application.
Questions that drive the decision
Ask these questions in order. Each narrows the choice.
- Is the shape of the data stable and shared? Stable, well-understood entities such as customers, accounts, and invoices belong in relational tables. Keys and constraints protect them.
- Does the same data need both document access and SQL access? If an application wants whole documents while reporting wants joins and aggregates, consider a duality view.
- Is the document produced by someone else and stored as received? Event payloads, API responses, and configuration blobs fit a JSON column. You keep them as they arrive.
- Do many writers update different parts of the same data? Duality views and relational tables handle this well. Rewriting a whole JSON document in a column makes writers collide.
- Do you filter or join on a few fields very often? Those fields are candidates for real columns, a function-based index, or a duality view over normalized tables.
Comparing the models
| Concern | Relational tables | JSON column | Duality view |
|---|---|---|---|
| Schema changes | `ALTER TABLE`, a deliberate step | None needed for new fields | Change the view, and the tables if needed |
| Data integrity | Types, keys, and constraints are enforced | Only `IS JSON` validity, plus whatever you add | Enforced by the underlying tables |
| Duplicate data | Stored once | A shared fact can be copied into many documents | Stored once |
| Reading a whole object | Joins needed | One column read | One document read, built by Oracle |
| Updating one field | Update one row | `JSON_TRANSFORM` or `JSON_MERGEPATCH` on the document | Update the document, and Oracle changes the affected rows |
| Ad hoc queries | Full SQL power | `JSON_TABLE`, dot notation, search index | SQL on the tables, or on the view |
| Concurrent writers | Row locks | Whole-document contention | ETag checks on the document |
| Oracle version | Any | 21c for the `JSON` type, earlier with `IS JSON` | 23ai |
The duplicate-data row is the one that most often surprises teams. Suppose each order document embeds the customer's name and city. When the customer moves, every order document that copied the city is now stale or needs rewriting. With normalized tables behind a duality view, the city exists once.
Pattern 1: relational core, JSON for the variable part
Many tables have a few fields you always query and a long tail you rarely do. Put the first group in columns and the tail in a JSON column.
CREATE TABLE events (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_type VARCHAR2(30) NOT NULL,
created_at TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL,
payload JSON
);
CREATE INDEX events_type_ix ON events (event_type, created_at);
SELECT e.id,
JSON_VALUE(e.payload, '$.user.id' RETURNING NUMBER) AS user_id
FROM events e
WHERE e.event_type = 'LOGIN'
AND e.created_at >= SYSTIMESTAMP - INTERVAL '1' DAY;The common filters use a normal B-tree index on real columns. The payload is parsed only for the rows that survive those filters. On a release before 21c, declare the column as CLOB CHECK (payload IS JSON) instead of JSON.
Pattern 2: generate JSON on demand
If your data is already relational and one endpoint needs JSON, you do not have to change storage. Build the document at query time with JSON_OBJECT and JSON_ARRAYAGG.
SELECT JSON_OBJECT(
'departmentName' VALUE d.name,
'employees' VALUE (
SELECT JSON_ARRAYAGG(
JSON_OBJECT('employeeId' VALUE e.employee_id,
'name' VALUE e.name))
FROM employee e
WHERE e.department_id = d.department_id)
) AS doc
FROM department d;This is read-only. You get a document but cannot write one back. If clients also need to write documents, a duality view does the same job and handles the writes, the validation of each change, and the ETag.
Pattern 3: a duality view for document APIs
Use a duality view when the business entity is naturally a document, such as a department with its employees, but the facts must stay shared and constrained. The tables carry foreign keys. The view defines which table each part of the document maps to and which operations are allowed (WITH INSERT UPDATE DELETE).
Choose a duality view over a JSON column when at least one of these holds:
- Other applications read or write the same data through SQL.
- The same child fact (an employee, a product) appears in more than one document type.
- You want referential integrity between parts of the data.
- Several clients update one document and you need optimistic concurrency.
Choose a JSON column over a duality view when the document is a self-contained unit that nobody else will join against. An example is a stored API response, a log record, or a form submission that you keep as received.
Gotchas that change the decision
- Duality views need 23ai. If production runs 19c, the choice is between relational tables and
IS JSONcolumns. Plan the upgrade before designing around the view. - Updatability is declared, not assumed. If a table in the view lacks
WITH UPDATE, writes to that part of the document fail. Decide per table which operations the document may perform. - Concurrency checks cost a retry. A client that sends a stale ETag is rejected and must re-read and retry. This is correct behavior, but the client code must handle it. With a plain JSON column, two writers can silently overwrite each other unless you build your own version check.
- A whole-document rewrite is expensive for large documents.
JSON_TRANSFORMon a nativeJSONcolumn edits the value without you rebuilding the text, but you should still treat a document with thousands of array elements as a sign to split it into rows. - Indexes follow your queries, not the model. A JSON search index is flexible but larger and slower to maintain than a function-based index on one field. If the same field is filtered on in every query, a function-based index (or a real column) is the better fit.
- JSON columns do not enforce your field types.
IS JSONonly checks that the text is valid JSON. A string"qty": "two"will be accepted. Use a JSON schema check or move the field to a column if the type matters. - Do not store everything as JSON by default. Teams that do this often rebuild relational structure later with
JSON_TABLEviews, which is slower and harder to constrain than the original columns.
A worked decision
Consider a shop with three data sets:
- Customers and orders. The structure is stable, orders reference customers, and finance runs SQL reports on them. Use relational tables. The mobile app wants an order as one document, so expose them through a duality view with
WITH INSERT UPDATEon the order lines. - Clickstream events. The fields vary by event type, nobody updates them, and queries filter by time and event type. Use the hybrid table from Pattern 1.
- Supplier catalog feeds. Each supplier sends a different layout and you keep the feed as received. Use a
JSONcolumn plus a JSON search index, and flatten withJSON_TABLEinto rows when you need to load the data into the product tables.
One database serves all three, and each data set uses the model that matches how it is changed and read.
Exercise
A team stores each customer order as a JSON document in a JSON column, with the customer's name and shipping address copied into every order. A support agent now needs to change a customer's address everywhere, and the finance team wants SQL reports that join orders to customers. Which model fits better, and why?
Show answer
Move the shared facts into relational tables (a customer table and an order table with a foreign key). If the application still needs order documents, expose them through a duality view (Oracle Database 23ai). The address is then stored once, so one update fixes every order. Foreign keys and constraints protect the data, finance can join the tables with ordinary SQL, and the application keeps reading and writing orders as documents. The copied-address design cannot do this, because each document would have to be found and rewritten.
Exercise
Name two cases where a plain JSON column is a better choice than a duality view.
Show answer
Any two of these: storing a document exactly as received from an external source, such as an API response or supplier feed. Storing records with fields that vary a lot between rows and are never joined to other tables, such as event payloads. Running on a release before 23ai, where duality views do not exist. In each case the document is a self-contained unit, so there are no shared facts to normalize.