Enjoyed this article?
Share it with your professional network and help others discover it.

Technical update — November 21, 2026. This article has been technically revised for MySQL 9.7. JSON Duality Views first appeared in MySQL 9.4.0 (July 22, 2025). MySQL 9.7.0 (April 21, 2026) added DML support for JSON Duality Views in MySQL Community Server and support for
AUTO_INCREMENTcolumns in Duality View DML. The originaldatemetadata above is retained as the page's historical publication date; it is not the date of this technical revision.
Modern application layers often consume hierarchical JSON. Frontends, REST clients, and AI agents can work naturally with a self-contained customer profile or support-ticket conversation. At the same time, enterprise applications commonly store this information in normalized relational tables so that primary keys, foreign keys, constraints, and transactions remain under database control.
Consider a customer-support question such as: “What open tickets does Alice have?” The application needs customer information and the customer's tickets. A traditional implementation might issue multiple queries and assemble the response in application code, or use an ORM and configure the relationships and loading strategy.
MySQL JSON Duality Views provide another interface: they map relational tables to hierarchical JSON documents. The relational tables remain the source of truth; the view describes how rows are represented as JSON. Depending on its table annotations, a Duality View can be read-only or can support JSON-document INSERT, UPDATE, and DELETE operations.
JSON Duality Views were introduced in MySQL 9.4.0. In MySQL 9.7.0, DML support became available in MySQL Community Server, and AUTO_INCREMENT columns became supported in Duality View DML. This article focuses on the MySQL 9.7 behavior and documents the example project's actual implementation rather than assuming that every operation uses a Duality View.
The companion project is a small customer-support ticket system built with three relational tables, two JSON Duality Views, a Python application, and a local AI agent.
The database exposes two document shapes:
ticket_conversation_dv returns one ticket with its customer and message history. It is read-only in this example.customer_profile_dv returns one customer with nested ticket summaries. It is configured for DML on the root customer object and its nested ticket objects.The Python application reads through the views. Its ticket-status update writes through customer_profile_dv. In the current companion implementation, ticket creation and message deletion use direct SQL against their base tables; they are not presented as Duality View writes. The AI agent reads customer and ticket documents through the views.
The diagram reflects the current repository implementation. MySQL REST Service is not included in the runnable Docker Compose setup, so it is not shown as a deployed component here. It can be explored separately as an optional integration, but it should not be described as a working feature of this repository unless a complete REST Service configuration is added and tested.
Duality Views do not remove the need for sound relational design. This example uses three InnoDB tables:
CREATE TABLE customers (
customer_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(120) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
tier ENUM('free', 'pro', 'enterprise') NOT NULL DEFAULT 'free',
PRIMARY KEY (customer_id)
) ENGINE=InnoDB;
CREATE TABLE support_tickets (
ticket_id INT NOT NULL AUTO_INCREMENT,
customer_id INT NOT NULL,
subject VARCHAR(300) NOT NULL,
status ENUM('open', 'in_progress', 'resolved', 'closed')
NOT NULL DEFAULT 'open',
priority ENUM('low', 'medium', 'high', 'critical')
NOT NULL DEFAULT 'medium',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (ticket_id),
CONSTRAINT fk_ticket_customer
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
ON DELETE CASCADE
) ENGINE=InnoDB;
CREATE TABLE ticket_messages (
message_id INT NOT NULL AUTO_INCREMENT,
ticket_id INT NOT NULL,
sender ENUM('customer', 'agent', 'system') NOT NULL,
body TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (message_id),
CONSTRAINT fk_message_ticket
FOREIGN KEY (ticket_id) REFERENCES support_tickets(ticket_id)
ON DELETE CASCADE
) ENGINE=InnoDB;The relationships are one-to-many: a customer can have multiple tickets, and a ticket can have multiple messages. Foreign keys preserve referential integrity. Each participating table has a primary key, which is a requirement for JSON Duality View definitions.
MySQL's CREATE JSON DUALITY VIEW statement maps a single root table to a JSON document. Related tables are projected through nested descendant subqueries:
JSON_DUALITY_OBJECT().JSON_ARRAYAGG(JSON_DUALITY_OBJECT(...))._id, mapped to the root table's primary key._id; use ordinary names such as customerId, ticketId, and messageId.The outer FROM clause must reference one root table. Do not put a JOIN in the root query. The relationship is expressed in the nested subquery's WHERE equality predicate.
ticket_conversation_dvThis view starts from support_tickets. It adds the customer as a singleton descendant and messages as a nested array. No DML annotations are specified, so the view and its descendants are read-only.
CREATE OR REPLACE JSON DUALITY VIEW ticket_conversation_dv AS
SELECT JSON_DUALITY_OBJECT(
'_id': t.ticket_id,
'subject': t.subject,
'status': t.status,
'priority': t.priority,
'createdAt': t.created_at,
'customer': (
SELECT JSON_DUALITY_OBJECT(
'customerId': c.customer_id,
'name': c.name,
'email': c.email,
'tier': c.tier
)
FROM customers c
WHERE c.customer_id = t.customer_id
),
'messages': (
SELECT JSON_ARRAYAGG(
JSON_DUALITY_OBJECT(
'messageId': m.message_id,
'sender': m.sender,
'body': m.body,
'sentAt': m.created_at
)
)
FROM ticket_messages m
WHERE m.ticket_id = t.ticket_id
)
)
FROM support_tickets t;The important structural details are:
support_tickets is the only table in the outer FROM clause.customers.customer_id = support_tickets.customer_id.ticket_messages.ticket_id = support_tickets.ticket_id._id appears only on the root ticket object. Nested primary keys are projected as customerId and messageId.A representative ticket document has this shape (the _metadata object, including its generated etag, is shown separately because its value is generated by MySQL):
{
"_id": 1,
"subject": "Cannot connect to production database",
"status": "open",
"priority": "critical",
"createdAt": "2025-06-01 09:15:00",
"customer": {
"customerId": 1,
"name": "Alice Johnson",
"email": "alice@techcorp.io",
"tier": "enterprise"
},
"messages": [
{
"messageId": 1,
"sender": "customer",
"body": "Our production database stopped responding at 9 AM. All services are down. Please help urgently!",
"sentAt": "2025-06-01 09:15:00"
}
]
}The order of elements in a JSON_ARRAYAGG() result should not be assumed unless the application explicitly defines and verifies an ordering strategy. The nested subquery syntax for a Duality View has specific restrictions; if chronological ordering is required, design and test that requirement separately rather than relying on incidental row order.
customer_profile_dvThis view starts from customers and projects the customer's tickets as a nested array. The root and nested ticket objects both carry INSERT, UPDATE, and DELETE annotations.
CREATE OR REPLACE JSON DUALITY VIEW customer_profile_dv AS
SELECT JSON_DUALITY_OBJECT(
WITH(INSERT, UPDATE, DELETE)
'_id': c.customer_id,
'name': c.name,
'email': c.email,
'tier': c.tier,
'tickets': (
SELECT JSON_ARRAYAGG(
JSON_DUALITY_OBJECT(
WITH(INSERT, UPDATE, DELETE)
'ticketId': t.ticket_id,
'subject': t.subject,
'status': t.status,
'priority': t.priority,
'createdAt': t.created_at
)
)
FROM support_tickets t
WHERE t.customer_id = c.customer_id
)
)
FROM customers c;Here, _id is reserved for the root customer object. The nested ticket primary key is exposed as ticketId. The annotations explicitly declare which DML operations are permitted for the customer and ticket objects. The view does not include ticket_messages, so message changes are not available through this view.
A JSON Duality View exposes its document through the data column:
-- Read ticket 1, including its customer and messages.
SELECT JSON_PRETTY(data)
FROM ticket_conversation_dv
WHERE data->'$._id' = 1;
-- Read customer 2 and the customer's nested ticket summaries.
SELECT JSON_PRETTY(data)
FROM customer_profile_dv
WHERE data->'$._id' = 2;MySQL also returns generated document metadata in _metadata; the etag value is generated by the server and should not be hard-coded in examples.
The companion Python application uses mysql-connector-python directly. It does not use SQLAlchemy or another ORM. The following example matches the repository's get_ticket() approach:
import json
import mysql.connector
DB_CONFIG = {
"host": "127.0.0.1",
"port": 3307,
"user": "root",
"password": "root123",
"database": "support_db",
}
def get_ticket(ticket_id: int) -> dict:
conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor()
try:
cursor.execute(
"SELECT JSON_PRETTY(data) "
"FROM ticket_conversation_dv "
"WHERE data->'$._id' = %s",
(ticket_id,),
)
row = cursor.fetchone()
return json.loads(row[0]) if row else {}
finally:
cursor.close()
conn.close()One SQL statement retrieves one complete ticket document from the view. The database constructs the nested customer and message structure; the Python function parses the returned JSON. This avoids having this particular read function issue separate queries to assemble each nested object. It does not mean that every possible ORM query causes N+1 queries or that every Duality View query is automatically faster; those are workload- and implementation-dependent questions.
The current repository's create_ticket() function uses a direct INSERT into support_tickets and then reads the updated customer document through customer_profile_dv:
cursor.execute(
"INSERT INTO support_tickets "
"(customer_id, subject, status, priority) "
"VALUES (%s, %s, 'open', %s)",
(customer_id, subject, priority),
)
conn.commit()
# Read the resulting customer document through the Duality View.
return get_customer(customer_id)This describes the code that is currently in app.py; it is not a claim that MySQL 9.7 cannot insert an auto-generated ticket through a Duality View. MySQL 9.7.0 documents support for AUTO_INCREMENT columns in Duality View DML, subject to the documented DML requirements. The companion application has not yet been changed to demonstrate ticket creation through customer_profile_dv, so this article does not claim that it does.
The current update_ticket_status() flow finds the owning customer, reads the complete customer document from customer_profile_dv, changes the matching ticketId, and writes the document back through the view. The essential update statement is:
cursor.execute(
"UPDATE customer_profile_dv "
"SET data = %s "
"WHERE data->'$._id' = %s",
(json.dumps(doc, default=str), customer_id),
)
conn.commit()The code updates the full document read from the view rather than constructing an incomplete replacement. This matters because the JSON document supplied for an update must match the view's projected shape; missing nested objects or array elements can be interpreted as deletions. The generated _metadata.etag should be retained from the read document when following MySQL's optimistic-concurrency workflow.
The current delete_message() function deletes directly from ticket_messages:
cursor.execute(
"DELETE FROM ticket_messages WHERE message_id = %s",
(message_id,),
)
conn.commit()This is a direct base-table operation in the companion application. ticket_conversation_dv is read-only, and customer_profile_dv does not project messages. A separate writable Duality View could be designed to expose message-level DML, but that view is not currently part of this repository. The article therefore does not claim that message deletion is performed through a Duality View.
The repository's agent.py uses a local Ollama model (llama3.2), LangChain Core tools, and LangGraph's create_react_agent. It defines database tools that read the customer profile and ticket conversation views. The language model receives the JSON returned by those tools and uses it to formulate an answer.
The implementation imports:
from langgraph.prebuilt import create_react_agent
from langchain_core.tools import tool
from langchain_ollama import ChatOllamaThe model configuration in the current repository is:
llm = ChatOllama(
model="llama3.2",
temperature=0,
)A representative tool reads a customer document from the updatable view (the agent itself uses the view for reading; it does not perform database writes):
@tool
def query_customer_tickets(customer_id: int) -> str:
"""Return a customer's profile and nested support tickets as JSON."""
conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor()
try:
cursor.execute(
"SELECT JSON_PRETTY(data) "
"FROM customer_profile_dv "
"WHERE data->'$._id' = %s",
(customer_id,),
)
row = cursor.fetchone()
return row[0] if row else json.dumps(
{"error": f"Customer {customer_id} not found."}
)
finally:
cursor.close()
conn.close()A second tool, query_ticket_details(), reads from ticket_conversation_dv and returns the customer and message history for one ticket. Example questions include:
The model should be treated as a natural-language interface, not as the source of truth. Database facts in the response must come from the tool results. The local model performs inference on the machine running Ollama; the model must be downloaded before use.
Dependency note: agent.py imports langgraph, but the repository's current requirements.txt does not list langgraph. Add langgraph to requirements.txt before relying on pip install -r requirements.txt alone, or install it explicitly in the environment:
pip install -r requirements.txt
pip install langgraph
ollama pull llama3.2
python agent.pyThe dependency file and the application should be kept in sync in the companion repository.
An ORM and a JSON Duality View solve related but different parts of the data-access problem. An ORM maps database rows to application objects. A Duality View defines a JSON document representation in the database. An application can use either approach, or combine them where appropriate.
| Concern | Traditional ORM | JSON Duality Views |
|---|---|---|
| Data mapping | Defined in application models and relationships | Defined by the database view |
| JSON document shape | Usually assembled or serialized by application code | Generated from the view definition |
| Nested reads | Depends on query and loading strategy | A selected view can return nested descendants in one document |
| N+1 behavior | Possible with unsuitable lazy-loading patterns; eager loading can avoid it | A single view query can retrieve its projected document hierarchy; workload still matters |
| Write path | ORM unit-of-work and generated SQL | DML against the JSON document, subject to annotations and view restrictions |
| Portability | ORM behavior varies by framework and database | MySQL-specific JSON Duality View definition and semantics |
| Performance | Depends on generated SQL, schema, indexes, and workload | Depends on view shape, schema, indexes, and workload |
This project does not include a controlled ORM-versus-Duality-View benchmark. Therefore, it makes no numerical performance claim. In particular, the earlier claim that Duality Views provide “up to 3× query throughput” has been removed because this repository does not provide the source benchmark, the test environment, the workload, or reproducible measurements needed to substantiate it.
The defensible benefit demonstrated by this example is reduced application-side JSON assembly for the specific reads implemented through the views. Any throughput or latency advantage must be measured for the application's actual schema and workload.
JSON Duality Views provide a useful document interface, but their definitions and DML operations have specific rules. Important MySQL 9.7 considerations include:
FROM table. A root-level JOIN is not supported. Related data is represented through nested descendant subqueries._id: the root object must expose its primary key as _id. No nested key may be named _id.WITH(INSERT, UPDATE, DELETE) annotations define which operations are allowed on each object. Without the relevant annotation, that object or sub-object is read-only.INSERT statement.REPLACE, LOAD DATA, LOAD XML, INSERT ... SELECT, INSERT ... ON DUPLICATE KEY UPDATE, and multi-table UPDATE or DELETE. EXPLAIN is also listed as unsupported for Duality View data-modification operations._metadata.etag. When an update is attempted, MySQL compares the current document state with the state last read. If the document changed, the update is rejected; the application can re-read and retry where appropriate.These are not reasons to avoid Duality Views. They are design constraints that should be understood and tested when selecting a document boundary and defining its write permissions.
| Consider JSON Duality Views when | Consider another approach when |
|---|---|
| An application repeatedly needs a stable hierarchical JSON document | The workload is dominated by analytical aggregations or broad scans |
| Multiple consumers need the same database-defined document shape | The document shape changes frequently in application-specific ways |
| You want selected JSON-document writes to map to related relational rows | You need bulk updates across many root documents in one operation |
| Referential integrity in relational tables remains important | The required relationship cannot be represented within the supported view rules |
| You want to reduce application-side nested JSON assembly | A conventional SQL query or ORM is simpler for the operation |
A practical design is to expose a focused Duality View for each stable document boundary, keep the relational schema authoritative, and use ordinary SQL for operations that are not a natural fit for document-level DML.
MySQL JSON Duality Views provide a database-defined way to expose normalized relational data as hierarchical JSON documents. In this support-ticket example, ticket_conversation_dv presents a ticket with its customer and messages, while customer_profile_dv presents a customer with nested ticket summaries and is annotated for DML.
The Python application uses the views for document reads and ticket-status updates. It uses direct SQL for ticket creation and message deletion in its current implementation. The local AI agent reads the same document views through LangChain tools orchestrated by LangGraph and Ollama.
The practical value is not a universal performance guarantee. It is the ability to define a reusable JSON document interface close to the data, while retaining relational tables and constraints underneath. Whether this reduces latency or improves throughput for a particular system must be established with a reproducible benchmark.
Source code: malek-al-edresi/json-duality-views-mysql-example
This is an updated technical version of the article. The companion repository should be kept synchronized with the SQL, dependency notes, and Python behavior described here. The article does not claim that performance benchmarks were run or that the public website has already been updated.