Working with JSON in SQL Server and MySQL (With Simple Examples)

JSON is everywhere: web APIs return it, online shops send orders in it, mobile apps store settings in it, and logs are full of it. Sooner or later some of it lands in your database, and someone asks for a report: “how many web orders came from Manama?” or “which products sold most through the app?”

Both SQL Server and MySQL can read, query and build JSON with plain SQL. This guide shows how, with one realistic example: storing orders as JSON, pulling out single values, turning arrays into rows, creating JSON from tables, and indexing JSON so queries stay fast. Then it answers the most important question: when you should not store data as JSON.

A JSON order document with customer, channel and items, read with JSON_VALUE for single values and OPENJSON or JSON_TABLE to turn the items array into rows

The sample data

An online shop sends each order as a JSON document. We store it as received:

{
  "customer": { "name": "Ali", "city": "Manama" },
  "channel": "web",
  "items": [
    { "sku": "KB-01", "qty": 2, "price": 25.50 },
    { "sku": "MS-02", "qty": 1, "price": 12.00 }
  ]
}

In SQL Server, JSON is stored as text in NVARCHAR(MAX) (SQL Server 2025 and Azure SQL also have a native json type). A CHECK constraint with ISJSON stops invalid documents getting in:

CREATE TABLE dbo.WebOrders (
    OrderID INT PRIMARY KEY,
    Details NVARCHAR(MAX) NOT NULL
        CONSTRAINT CK_WebOrders_Details CHECK (ISJSON(Details) = 1)
);

INSERT INTO dbo.WebOrders VALUES
(1, N'{"customer":{"name":"Ali","city":"Manama"},"channel":"web",
       "items":[{"sku":"KB-01","qty":2,"price":25.50},{"sku":"MS-02","qty":1,"price":12.00}]}'),
(2, N'{"customer":{"name":"Sara","city":"Riffa"},"channel":"app",
       "items":[{"sku":"LS-10","qty":1,"price":39.90}]}'),
(3, N'{"customer":{"name":"Omar","city":"Manama"},"channel":"web","coupon":"NOV10",
       "items":[{"sku":"KB-01","qty":1,"price":25.50},{"sku":"HP-05","qty":1,"price":59.00}]}');

In MySQL, use the JSON data type, which validates the document and stores it in an efficient binary format:

CREATE TABLE WebOrders (
    OrderID INT PRIMARY KEY,
    Details JSON NOT NULL
);

JSON paths in one minute

Every function below uses a path to point inside the document:

PathMeans
$The whole document
$.channelThe channel property
$.customer.citycity inside customer
$.items[0]The first item in the items array (arrays count from 0)
$.items[0].skuThe sku of the first item

Reading single values: JSON_VALUE

JSON_VALUE returns one scalar value (text, number, true/false) as text:

SELECT OrderID,
       JSON_VALUE(Details, '$.customer.name') AS Customer,
       JSON_VALUE(Details, '$.customer.city') AS City,
       JSON_VALUE(Details, '$.coupon')        AS Coupon
FROM dbo.WebOrders;
OrderIDCustomerCityCoupon
1AliManamaNULL
2SaraRiffaNULL
3OmarManamaNOV10

A property that doesn’t exist (only order 3 has a coupon) returns NULL instead of an error. That’s the default lax mode. Write 'strict $.coupon' if a missing property should raise an error instead.

Use it in WHERE like any expression:

SELECT OrderID
FROM dbo.WebOrders
WHERE JSON_VALUE(Details, '$.customer.city') = 'Manama';   -- 1 and 3

JSON_VALUE works the same way in MySQL 8.0.21 and later. MySQL also has a shorter operator:

SELECT OrderID, Details->>'$.customer.name' AS Customer   -- MySQL
FROM WebOrders;

->> returns the value as plain text; -> returns it as JSON (with the quotes).

Objects and arrays aren’t scalar values, so JSON_VALUE returns NULL for them. Use JSON_QUERY to get a fragment of JSON instead:

SELECT JSON_QUERY(Details, '$.items') AS ItemsJson FROM dbo.WebOrders WHERE OrderID = 2;
-- [{"sku":"LS-10","qty":1,"price":39.90}]

Turning arrays into rows: OPENJSON and JSON_TABLE

Reports need one row per order line, not one JSON array per order. In SQL Server, OPENJSON with a WITH clause turns the array into a table, and CROSS APPLY runs it for each order:

SELECT o.OrderID, i.sku, i.qty, i.price, i.qty * i.price AS LineTotal
FROM dbo.WebOrders AS o
CROSS APPLY OPENJSON(o.Details, '$.items')
     WITH (
         sku   VARCHAR(20)   '$.sku',
         qty   INT           '$.qty',
         price DECIMAL(10,2) '$.price'
     ) AS i
ORDER BY o.OrderID, i.sku;
OrderIDskuqtypriceLineTotal
1KB-01225.5051.00
1MS-02112.0012.00
2LS-10139.9039.90
3HP-05159.0059.00
3KB-01125.5025.50

The WITH clause gives each value a column name and a real data type, so qty * price is proper decimal arithmetic. OPENJSON needs database compatibility level 130 (SQL Server 2016) or higher.

MySQL 8 uses the standard JSON_TABLE:

SELECT o.OrderID, i.sku, i.qty, i.price, i.qty * i.price AS LineTotal
FROM WebOrders AS o,
     JSON_TABLE(o.Details, '$.items[*]'
         COLUMNS (
             sku   VARCHAR(20)   PATH '$.sku',
             qty   INT           PATH '$.qty',
             price DECIMAL(10,2) PATH '$.price'
         )) AS i
ORDER BY o.OrderID, i.sku;

Once the lines are rows, everything you know about SQL works. Best-selling products:

SELECT i.sku, SUM(i.qty) AS Units, SUM(i.qty * i.price) AS Revenue
FROM dbo.WebOrders AS o
CROSS APPLY OPENJSON(o.Details, '$.items')
     WITH (sku VARCHAR(20) '$.sku', qty INT '$.qty', price DECIMAL(10,2) '$.price') AS i
GROUP BY i.sku
ORDER BY Revenue DESC;
skuUnitsRevenue
KB-01376.50
HP-05159.00
LS-10139.90
MS-02112.00

Changing a value: JSON_MODIFY

UPDATE dbo.WebOrders
SET Details = JSON_MODIFY(Details, '$.channel', 'phone')
WHERE OrderID = 2;

JSON_MODIFY returns the updated document; you still write it back with UPDATE. Setting a value to NULL removes the property in lax mode. MySQL uses JSON_SET, JSON_INSERT, JSON_REPLACE and JSON_REMOVE.

Creating JSON from tables: FOR JSON

Going the other way (building JSON to send to an API or a web page) is often more useful than reading it. In SQL Server, add FOR JSON PATH to any query; dots in column aliases create nested objects:

SELECT c.CustomerID AS id,
       c.Name       AS [customer.name],
       c.City       AS [customer.city]
FROM dbo.Customers AS c
WHERE c.CustomerID = 1
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER;
-- {"id":1,"customer":{"name":"Ali","city":"Manama"}}

A subquery with its own FOR JSON PATH becomes a nested array, so one query can return an invoice header with its lines. Without WITHOUT_ARRAY_WRAPPER the result is an array [...], which is what you want for a list of rows.

In MySQL, use JSON_OBJECT and JSON_ARRAYAGG:

SELECT JSON_OBJECT('id', CustomerID,
                   'customer', JSON_OBJECT('name', Name, 'city', City)) AS doc
FROM Customers
WHERE CustomerID = 1;

Making JSON queries fast

WHERE JSON_VALUE(Details, '$.customer.city') = 'Manama' has to open and parse every document: a full scan. You can’t index inside an NVARCHAR(MAX) column directly, but you can index a computed column built from it:

ALTER TABLE dbo.WebOrders
    ADD City AS JSON_VALUE(Details, '$.customer.city');

CREATE INDEX IX_WebOrders_City ON dbo.WebOrders (City);

SQL Server can now use the index for the original WHERE JSON_VALUE(...) query as well as for WHERE City = 'Manama', as long as the expression matches exactly. JSON_VALUE returns NVARCHAR(4000), so SQL Server warns that the index key could be too long; define the column as CAST(JSON_VALUE(Details, '$.customer.city') AS NVARCHAR(50)) to avoid that (and use the same CAST expression in queries). (If the index isn’t used, read the plan as shown in How to Read a SQL Server Execution Plan.)

MySQL uses a generated column the same way:

ALTER TABLE WebOrders
    ADD City VARCHAR(50) AS (Details->>'$.customer.city'),
    ADD INDEX ix_city (City);

MySQL 8.0.17+ can also index every value of an array with a multi-valued index, for example to find orders containing a given SKU.

When not to store JSON

JSON columns are flexible, and that’s the danger. Use this rule:

  • Store as JSON when you keep the document mostly as a whole: the raw API response for auditing, user preferences, optional attributes that differ for every product category, data you receive but rarely query.
  • Use normal columns and tables for anything you filter, join, sum or must keep consistent: customer, dates, amounts, quantities, status.

In the example above, a real system would copy the customer and the order lines into proper Orders and OrderLines tables when the order arrives (with OPENJSON in an INSERT ... SELECT), and keep the raw JSON only as a record of what was received. Proper columns give you data types, NOT NULL, foreign keys and normal indexes, which JSON can’t. A table that holds everything in one JSON column is the modern version of the Entity-Attribute-Value antipattern (see our SQL Antipatterns review).

Common mistakes

  • No ISJSON check in SQL Server, so a broken document breaks every report.
  • Using JSON_VALUE for an object or array and getting NULL. Use JSON_QUERY (or OPENJSON) for those.
  • Comparing numbers as text: JSON_VALUE returns text, so '9' > '10'. Cast it, or use OPENJSON ... WITH with real types.
  • Forgetting that paths are case-sensitive: $.Customer doesn’t find "customer".
  • Filtering large tables on JSON values without a computed or generated column and an index.
  • Storing core business data as JSON to avoid designing tables.

Practice exercises

Exercise 1. Return each order’s ID, channel and number of items. (Hint: in SQL Server, count the rows from OPENJSON(Details, '$.items'); in MySQL, use JSON_LENGTH.)

Exercise 2. Return the total value of each order (sum of qty * price) with the customer’s name.

Exercise 3. Write a query that finds all orders that used a coupon.

Answers

Answer 1.

SELECT o.OrderID,
       JSON_VALUE(o.Details, '$.channel') AS Channel,
       (SELECT COUNT(*) FROM OPENJSON(o.Details, '$.items')) AS ItemCount
FROM dbo.WebOrders AS o;
-- MySQL: JSON_LENGTH(Details, '$.items') AS ItemCount

Order 1: web, 2. Order 2: app, 1. Order 3: web, 2.

Answer 2.

SELECT o.OrderID,
       JSON_VALUE(o.Details, '$.customer.name') AS Customer,
       SUM(i.qty * i.price) AS OrderTotal
FROM dbo.WebOrders AS o
CROSS APPLY OPENJSON(o.Details, '$.items')
     WITH (qty INT '$.qty', price DECIMAL(10,2) '$.price') AS i
GROUP BY o.OrderID, JSON_VALUE(o.Details, '$.customer.name');

Ali 63.00, Sara 39.90, Omar 84.50.

Answer 3.

SELECT OrderID, JSON_VALUE(Details, '$.coupon') AS Coupon
FROM dbo.WebOrders
WHERE JSON_VALUE(Details, '$.coupon') IS NOT NULL;

Only order 3 (NOV10).

Summary

  • SQL Server stores JSON in NVARCHAR(MAX) (protect it with CHECK (ISJSON(...) = 1)); MySQL has a JSON type.
  • JSON_VALUE reads one value; JSON_QUERY reads an object or array.
  • OPENJSON ... WITH (SQL Server) and JSON_TABLE (MySQL) turn arrays into rows, so you can join, group and sum.
  • FOR JSON PATH (SQL Server) and JSON_OBJECT / JSON_ARRAYAGG (MySQL) build JSON from tables.
  • Index a computed or generated column to make JSON filters fast.
  • Keep anything you filter, join or total in real columns; use JSON for documents you mostly store whole.

Related articles

Scroll to Top