JSON

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

MySQL has a native JSON column type that validates documents on write, stores them in a binary format and offers a large function library for reading, changing and indexing them. This page uses the tags and attrs columns of the products table from the shop example (see Getting Started). Every statement and every result shown was run on the mysql:latest image, which reported server version 26.10.0. The tables show the client’s --table output; long results are trimmed. For the engine-agnostic SQL/JSON picture see JSON & XML functions.

The JSON type and its binary storage

A JSON column is not a TEXT column with a constraint. On insert the server parses the text, rejects anything that is not valid JSON, and stores a binary representation that lets it jump straight to a member or array element without re-parsing the whole document. Invalid text is refused with error 3140:

INSERT INTO products VALUES ('Z-1','x','x',1,1,'[oops','{}');
ERROR 3140 (22032): Invalid JSON text: "Invalid value." at position 1 in value for column 'products.tags'.

Because the document is normalised when it is stored, what you read back is not what you wrote. Whitespace is dropped and re-formatted, duplicate keys keep only the last value, and members are sorted (shorter keys first, then by bytes). A TEXT column keeps the original text byte for byte:

CREATE TEMPORARY TABLE t_txt (doc text);
INSERT INTO t_txt VALUES ('{"a":1,"a":2, "b" : [1,2]}');
CREATE TEMPORARY TABLE t_json (doc json);
INSERT INTO t_json SELECT doc FROM t_txt;
SELECT doc FROM t_txt;
SELECT doc FROM t_json;
+----------------------------+
| doc                        |
+----------------------------+
| {"a":1,"a":2, "b" : [1,2]} |
+----------------------------+
+-----------------------+
| doc                   |
+-----------------------+
| {"a": 2, "b": [1, 2]} |
+-----------------------+
JSON TEXT holding JSON

Validation on write

yes, error 3140

none (check with JSON_VALID)

Stored form

binary, members addressable

raw text, parsed on every access

Key order and duplicates

normalised, last duplicate wins

preserved as written

Path access cost

direct lookup

full parse per row

Indexable through

generated columns, functional and multi-valued indexes

generated columns only

Typical reason to choose it

queried or modified documents

storing a payload verbatim

Choose TEXT only when the exact bytes matter (for example a signed webhook body). Anything you query or update belongs in JSON. The binary form also means the JSON type has no collation of its own: the strings inside always use utf8mb4 and the utf8mb4_bin collation.

SELECT JSON_TYPE(attrs), JSON_VALID('{"a":1}'), JSON_LENGTH(tags), JSON_KEYS(attrs)
FROM products WHERE sku='A-1';
+------------------+-----------------------+-------------------+-------------------------------------+
| JSON_TYPE(attrs) | JSON_VALID('{"a":1}') | JSON_LENGTH(tags) | JSON_KEYS(attrs)                    |
+------------------+-----------------------+-------------------+-------------------------------------+
| OBJECT           |                     1 |                 2 | ["color", "width_cm", "adjustable"] |
+------------------+-----------------------+-------------------+-------------------------------------+

Path syntax

Most JSON functions take a path, a string that starts at the document root $ and walks down. The shape of a path is the same everywhere (functions, operators, JSON_TABLE columns, index definitions).

Path Meaning

$

the whole document

$.key

member of an object

$."a b"

member whose name is not a plain identifier needs double quotes

$[2]

array element by zero-based position

$[last], $[last-1]

last element, one before last

$[0 to 1]

a range of elements

$[*]

every element of an array

$.*

every member value of an object

$**.key

every key at any depth (a wildcard path)

SELECT JSON_EXTRACT('{"a":{"b":[10,20,{"c":3}]}}','$.a.b[2].c'),
       JSON_EXTRACT('{"a":{"b":[10,20,{"c":3}]}}','$.a.b[last-1]'),
       JSON_EXTRACT('{"a":{"b":[10,20,{"c":3}]}}','$**.c');
SELECT JSON_EXTRACT(tags,'$[*]'), JSON_EXTRACT(tags,'$[last]'),
       JSON_EXTRACT(tags,'$[0 to 1]'), JSON_EXTRACT(attrs,'$**.color')
FROM products WHERE sku='A-2';
+----------------------------------------------------------+-------------------------------------------------------------+-----------------------------------------------------+
| JSON_EXTRACT('{"a":{"b":[10,20,{"c":3}]}}','$.a.b[2].c') | JSON_EXTRACT('{"a":{"b":[10,20,{"c":3}]}}','$.a.b[last-1]') | JSON_EXTRACT('{"a":{"b":[10,20,{"c":3}]}}','$**.c') |
+----------------------------------------------------------+-------------------------------------------------------------+-----------------------------------------------------+
| 3                                                        | 20                                                          | [3]                                                 |
+----------------------------------------------------------+-------------------------------------------------------------+-----------------------------------------------------+
+---------------------------------+------------------------------+--------------------------------+---------------------------------+
| JSON_EXTRACT(tags,'$[*]')       | JSON_EXTRACT(tags,'$[last]') | JSON_EXTRACT(tags,'$[0 to 1]') | JSON_EXTRACT(attrs,'$**.color') |
+---------------------------------+------------------------------+--------------------------------+---------------------------------+
| ["office", "ergonomic", "sale"] | "sale"                       | ["office", "ergonomic"]        | ["black"]                       |
+---------------------------------+------------------------------+--------------------------------+---------------------------------+

A path that matches nothing returns SQL NULL, not an error, which is convenient for sparse documents. A path that is syntactically wrong is an error (3143): $.a b fails, $."a b" works.

Reading: ->, ->> and JSON_EXTRACT

JSON_EXTRACT(doc, path) returns a JSON value, so a string comes back with its quotes. The column-path operator -> is shorthand for it, and ->> is shorthand for JSON_UNQUOTE(JSON_EXTRACT(...)), which returns a plain SQL string:

SELECT sku, attrs->'$.color' AS c, attrs->>'$.color' AS c_text, JSON_EXTRACT(attrs,'$.width_cm') w
FROM products;
+-----+---------+--------+------+
| sku | c       | c_text | w    |
+-----+---------+--------+------+
| A-1 | "oak"   | oak    | 160  |
| A-2 | "black" | black  | NULL |
| B-7 | "white" | white  | NULL |
| C-3 | NULL    | NULL   | NULL |
| C-9 | NULL    | NULL   | NULL |
+-----+---------+--------+------+

Use ->> in SELECT lists and WHERE clauses that compare to strings. The operators work only on a column reference, not on an arbitrary expression; for expressions call JSON_EXTRACT. JSON_VALUE(doc, path RETURNING type) extracts and casts in one step, which is the clearest way to get a typed scalar:

SELECT JSON_VALUE(attrs,'$.width_cm' RETURNING UNSIGNED) FROM products WHERE sku='A-1';
+---------------------------------------------------+
| JSON_VALUE(attrs,'$.width_cm' RETURNING UNSIGNED) |
+---------------------------------------------------+
|                                               160 |
+---------------------------------------------------+

Comparisons

JSON values compare by JSON type rules, so numbers inside documents compare as numbers, not as text. When a JSON value is compared with a string, the string is converted to a JSON string first:

SELECT JSON_EXTRACT('{"n":10}','$.n') > JSON_EXTRACT('{"n":9}','$.n') AS numeric_cmp, '10' < '9' AS string_cmp;
SELECT attrs->'$.color' = 'oak' AS direct, attrs->>'$.color' = 'oak' AS unquoted
FROM products WHERE sku='A-1';
+-------------+------------+
| numeric_cmp | string_cmp |
+-------------+------------+
|           1 |          1 |
+-------------+------------+
+--------+----------+
| direct | unquoted |
+--------+----------+
|      1 |        1 |
+--------+----------+

Both work, but they take different paths through the optimizer, which matters for indexing (see below).

Testing membership

Three predicates test whether a document holds a value; they are the building blocks for tag queries.

SELECT sku FROM products WHERE JSON_CONTAINS(tags,'"sale"');
SELECT sku FROM products WHERE 'sale' MEMBER OF (tags);
SELECT sku FROM products WHERE JSON_OVERLAPS(tags,'["sale","led"]');
SELECT JSON_CONTAINS(attrs,'{"color":"oak"}') FROM products WHERE sku='A-1';
sku: A-2, C-3             (JSON_CONTAINS and MEMBER OF)
sku: A-2, B-7, C-3        (JSON_OVERLAPS: any of the listed tags)
JSON_CONTAINS(attrs,'{"color":"oak"}') = 1

(The result sets are summarised in one line each here; the server printed ordinary one-column tables.)

  • JSON_CONTAINS(target, candidate) is true when the candidate document is contained in the target. A scalar candidate must be written as JSON (note the '"sale"' quotes); an object candidate matches when every member of the candidate is present.

  • value MEMBER OF (json_array) tests a single value against an array and is the simplest form for tag lookups.

  • JSON_OVERLAPS(a, b) is true when the two documents share at least one element (arrays) or member (objects).

  • JSON_CONTAINS_PATH(doc, 'one'|'all', path...) tests only for the existence of paths; JSON_SEARCH(doc, 'one'|'all', string) returns the path of a string value ("$[2]" for sale in the A-2 tags).

Changing documents

The modifying functions return a new document; combine them with UPDATE to store it. They differ only in what they do when the path exists or not:

Function Behaviour

JSON_SET

replaces an existing value and adds a missing one (upsert)

JSON_INSERT

adds a missing value, never overwrites

JSON_REPLACE

overwrites an existing value, never adds

JSON_REMOVE

deletes the path

JSON_ARRAY_APPEND / JSON_ARRAY_INSERT

add elements to an array at the end or at a position

JSON_MERGE_PATCH

RFC 7396 merge, null deletes a member

JSON_MERGE_PRESERVE

merge that keeps duplicate keys by making arrays

SELECT JSON_SET(attrs,'$.color','walnut','$.weight_kg',30) FROM products WHERE sku='A-1';
SELECT JSON_INSERT(attrs,'$.color','walnut','$.weight_kg',30) FROM products WHERE sku='A-1';
SELECT JSON_REPLACE(attrs,'$.color','walnut','$.weight_kg',30) FROM products WHERE sku='A-1';
SELECT JSON_REMOVE(attrs,'$.adjustable') FROM products WHERE sku='A-1';
JSON_SET:     {"color": "walnut", "width_cm": 160, "weight_kg": 30, "adjustable": true}
JSON_INSERT:  {"color": "oak", "width_cm": 160, "weight_kg": 30, "adjustable": true}
JSON_REPLACE: {"color": "walnut", "width_cm": 160, "adjustable": true}
JSON_REMOVE:  {"color": "oak", "width_cm": 160}
SELECT JSON_ARRAY_APPEND(tags,'$','new'), JSON_ARRAY_INSERT(tags,'$[0]','first')
FROM products WHERE sku='A-1';
SELECT JSON_MERGE_PATCH(attrs,'{"color":null,"x":1}'), JSON_MERGE_PRESERVE('{"a":1}','{"a":2}')
FROM products WHERE sku='A-2';
+-----------------------------------+----------------------------------------+
| JSON_ARRAY_APPEND(tags,'$','new') | JSON_ARRAY_INSERT(tags,'$[0]','first') |
+-----------------------------------+----------------------------------------+
| ["office", "ergonomic", "new"]    | ["first", "office", "ergonomic"]       |
+-----------------------------------+----------------------------------------+
+------------------------------------------------+------------------------------------------+
| JSON_MERGE_PATCH(attrs,'{"color":null,"x":1}') | JSON_MERGE_PRESERVE('{"a":1}','{"a":2}') |
+------------------------------------------------+------------------------------------------+
| {"x": 1, "mesh": true}                         | {"a": [1, 2]}                            |
+------------------------------------------------+------------------------------------------+

Updating a row in place is an ordinary UPDATE:

UPDATE products SET attrs = JSON_SET(attrs,'$.stock_note','low') WHERE sku='A-1';
SELECT attrs FROM products WHERE sku='A-1';
UPDATE products SET attrs = JSON_REMOVE(attrs,'$.stock_note') WHERE sku='A-1';
SELECT attrs FROM products WHERE sku='A-1';
{"color": "oak", "width_cm": 160, "adjustable": true, "stock_note": "low"}
{"color": "oak", "width_cm": 160, "adjustable": true}

Partial updates

When a statement changes a JSON column only through JSON_SET, JSON_REPLACE or JSON_REMOVE on that same column, InnoDB can rewrite just the changed bytes instead of the whole document (a partial update), provided the new value is not larger than the old one or fits in the space the old one left. JSON_STORAGE_SIZE and JSON_STORAGE_FREE show the stored size and the space freed by earlier partial updates:

SELECT JSON_STORAGE_SIZE(attrs), JSON_STORAGE_FREE(attrs) FROM products WHERE sku='A-1';
+--------------------------+--------------------------+
| JSON_STORAGE_SIZE(attrs) | JSON_STORAGE_FREE(attrs) |
+--------------------------+--------------------------+
|                       53 |                        0 |
+--------------------------+--------------------------+

Partial updates matter most for large documents. The same optimisation can be carried into the binary log so replicas receive a diff rather than the full document: that is controlled by binlog_row_value_options, which is empty (off) by default on this server and is set to PARTIAL_JSON to enable it. See Replication & High Availability.

Aggregating into JSON

JSON_ARRAYAGG and JSON_OBJECTAGG turn a group of rows into a document, which is how you return nested results from one query:

SELECT category, JSON_ARRAYAGG(name) names FROM products GROUP BY category;
SELECT JSON_OBJECTAGG(sku, price) FROM products;
SELECT c.name, JSON_ARRAYAGG(JSON_OBJECT('order', o.id, 'status', o.status)) orders
FROM customers c JOIN orders o ON o.customer_id=c.id GROUP BY c.id;
+-------------+-----------------------------------+
| category    | names                             |
+-------------+-----------------------------------+
| electronics | ["USB-C Hub", "Monitor 27in"]     |
| furniture   | ["Standing Desk", "Office Chair"] |
| lighting    | ["Desk Lamp"]                     |
+-------------+-----------------------------------+
+---------------------------------------------------------------------------+
| JSON_OBJECTAGG(sku, price)                                                |
+---------------------------------------------------------------------------+
| {"A-1": 349.00, "A-2": 189.50, "B-7": 24.99, "C-3": 39.00, "C-9": 279.00} |
+---------------------------------------------------------------------------+
+----------------+-----------------------------------------------------------------------------------------------------------------+
| name           | orders                                                                                                          |
+----------------+-----------------------------------------------------------------------------------------------------------------+
| Ada Lovelace   | [{"order": 1001, "status": "shipped"}, {"order": 1002, "status": "open"}, {"order": 1007, "status": "shipped"}] |
| Alan Turing    | [{"order": 1003, "status": "shipped"}, {"order": 1008, "status": "open"}]                                       |
| Grace Hopper   | [{"order": 1004, "status": "shipped"}, {"order": 1005, "status": "cancelled"}]                                  |
| Linus Torvalds | [{"order": 1006, "status": "open"}]                                                                             |
+----------------+-----------------------------------------------------------------------------------------------------------------+

The element order inside an aggregated array is not guaranteed unless the rows are ordered first (for example through an ordered subquery). Over an empty set JSON_ARRAYAGG returns NULL, not [].

Shredding with JSON_TABLE

JSON_TABLE is the reverse: it turns a document into rows and typed columns, usable in FROM like any table and joinable laterally to the row that supplies the document. The shop’s tags become one row per tag:

SELECT p.sku, t.tag
FROM products p,
     JSON_TABLE(p.tags,'$[*]' COLUMNS (tag varchar(20) PATH '$')) t
WHERE p.category='furniture';
+-----+-----------+
| sku | tag       |
+-----+-----------+
| A-1 | office    |
| A-1 | ergonomic |
| A-2 | office    |
| A-2 | ergonomic |
| A-2 | sale      |
+-----+-----------+

Once shredded, relational operators apply. Counting tags and joining to order lines to get revenue per tag:

SELECT tag, COUNT(*) n FROM products p,
  JSON_TABLE(p.tags,'$[*]' COLUMNS (tag varchar(20) PATH '$')) t
GROUP BY tag ORDER BY n DESC, tag;

SELECT t.tag, SUM(oi.qty*oi.price) revenue
FROM products p JOIN order_items oi ON oi.sku=p.sku,
     JSON_TABLE(p.tags,'$[*]' COLUMNS(tag varchar(20) PATH '$')) t
GROUP BY t.tag ORDER BY revenue DESC;
+-----------+---+        +-----------+---------+
| tag       | n |        | tag       | revenue |
+-----------+---+        +-----------+---------+
| office    | 4 |        | office    | 3031.42 |
| ergonomic | 2 |        | ergonomic | 1994.50 |
| sale      | 2 |        | sale      | 1103.50 |
| display   | 1 |        | display   |  837.00 |
| led       | 1 |        | led       |  199.92 |
| usb       | 1 |        | usb       |  156.00 |
+-----------+---+        +-----------+---------+

(Two result sets, laid out side by side here to save space.) Object documents shred through column definitions, which can supply defaults, test for the existence of a path and number the rows:

SELECT p.sku, a.*
FROM products p,
     JSON_TABLE(p.attrs,'$' COLUMNS (
       color    varchar(20) PATH '$.color' DEFAULT '"n/a"' ON EMPTY,
       watts    int         PATH '$.watts' DEFAULT '0' ON EMPTY,
       has_mesh bool        EXISTS PATH '$.mesh',
       ord FOR ORDINALITY)) a;
+-----+-------+-------+----------+------+
| sku | color | watts | has_mesh | ord  |
+-----+-------+-------+----------+------+
| A-1 | oak   |     0 |        0 |    1 |
| A-2 | black |     0 |        1 |    1 |
| B-7 | white |     9 |        0 |    1 |
| C-3 | n/a   |     0 |        0 |    1 |
| C-9 | n/a   |     0 |        0 |    1 |
+-----+-------+-------+----------+------+

NESTED PATH descends into an inner array or object and repeats the outer columns for each inner element. Applied to every value of the C-3 attributes with $.* it yields one row per value (7 and 100). A column can also use ON ERROR clauses (NULL, DEFAULT, ERROR) to decide what happens when a value cannot be converted.

Indexing JSON

A JSON column cannot be indexed directly, and without a supporting index a predicate on a path scans every row. This section uses a 50,000-row table built from a recursive CTE, because the five shop products are too few for the optimizer to prefer an index:

SET SESSION cte_max_recursion_depth = 100000;
CREATE TABLE items (
  id int PRIMARY KEY,
  tags json NOT NULL,
  attrs json NOT NULL
);
INSERT INTO items
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i < 50000)
SELECT i,
       JSON_ARRAY(ELT(1+i%5,'office','led','usb','sale','display'), CONCAT('t', i%1000)),
       JSON_OBJECT('color', ELT(1+i%4,'oak','black','white','red'), 'watts', i%200, 'sku', CONCAT('S-', i))
FROM n;

Baseline, with no index: the plan is a full table scan with the JSON functions evaluated on every row.

EXPLAIN SELECT id FROM items WHERE attrs->>'$.sku' = 'S-4242';
-> Filter: (json_unquote(json_extract(items.attrs,'$.sku')) = 'S-4242')  (cost=5000 rows=50000)
    -> Table scan on items  (cost=5000 rows=50000)
flowchart TD Q["Predicate on a JSON path"] --> A{"One scalar value per row?"} A -- yes --> B["Functional index on the path, or a generated column plus index"] A -- "no, an array of values" --> C["Multi-valued index: CAST(... AS type ARRAY)"] B --> D["Use MEMBER OF / = / range predicates"] C --> E["Use MEMBER OF, JSON_CONTAINS, JSON_OVERLAPS"] Q --> F["Many unknown paths"] --> G["Promote hot paths to columns, keep the rest as JSON"]

Generated columns

A generated column computes a value from the document; it can be VIRTUAL (computed on read, the default) or STORED (computed on write and kept in the row). A secondary index on it turns the path into an ordinary indexed column:

ALTER TABLE items
  ADD COLUMN sku varchar(20) GENERATED ALWAYS AS (attrs->>'$.sku') VIRTUAL,
  ADD INDEX idx_sku (sku);
EXPLAIN SELECT id FROM items WHERE sku = 'S-4242';
EXPLAIN SELECT id FROM items WHERE attrs->>'$.sku' = 'S-4242';
-> Covering index lookup on items using idx_sku (sku = 'S-4242')  (cost=0.653 rows=1)
-> Index lookup on items using idx_sku (sku = 'S-4242')  (cost=0.35 rows=1)

The second query still names the JSON path, yet the optimizer recognises the expression and substitutes the generated column, so existing queries benefit without a rewrite. The generated column also appears in SELECT * and can be used in other indexes, foreign keys and views.

Functional indexes

A functional index (a functional key part) indexes an expression directly, with no visible column. The expression must be wrapped in its own parentheses, and a CAST fixes the type of the index entries:

CREATE INDEX idx_watts ON items ((CAST(attrs->>'$.watts' AS UNSIGNED)));
EXPLAIN SELECT id FROM items WHERE CAST(attrs->>'$.watts' AS UNSIGNED) = 77;
EXPLAIN SELECT id FROM items WHERE attrs->>'$.watts' = 77;
-> Index lookup on items using idx_watts (cast(json_unquote(json_extract(attrs,_latin1'$.watts')) as unsigned) = 77)  (cost=87.5 rows=250)
-> Index lookup on items using idx_watts (cast(json_unquote(json_extract(attrs,_latin1'$.watts')) as unsigned) = 77)  (cost=87.5 rows=250)

Here too the unadorned comparison attrs->>'$.watts' = 77 is rewritten to match the index. Internally a functional index is a hidden virtual generated column plus an index, which is why SHOW INDEX lists it with NULL as the column name and the expression in the Expression column.

Multi-valued indexes

A path that yields an array needs a multi-valued index: one index entry per array element, declared with CAST(... AS type ARRAY). The cast type decides how elements are stored (CHAR(n), UNSIGNED, SIGNED, DATE, DATETIME, DECIMAL and others):

CREATE INDEX idx_tags ON items ((CAST(tags->'$' AS CHAR(20) ARRAY)));
EXPLAIN SELECT id FROM items WHERE 't7' MEMBER OF (tags->'$');
EXPLAIN SELECT id FROM items WHERE JSON_CONTAINS(tags->'$','"t7"');
EXPLAIN SELECT id FROM items WHERE JSON_OVERLAPS(tags->'$','["t7","t8"]');
SELECT COUNT(*) FROM items WHERE 't7' MEMBER OF (tags->'$');
-> Filter: json'"t7"' member of (cast(json_extract(tags,_latin1'$') as char(20) array))  (cost=17.5 rows=50)
    -> Index lookup on items using idx_tags (cast(json_extract(tags,_latin1'$') as char(20) array) = json'"t7"')  (cost=17.5 rows=50)

-> Filter: json_contains(cast(json_extract(tags,_latin1'$') as char(20) array),json'["t7"]')  (cost=22.8 rows=50)
    -> Index range scan on items using idx_tags over ('t7' MEMBER OF (json_extract(tags,_latin1'$')))  (cost=22.8 rows=50)

-> Filter: json_overlaps(cast(json_extract(tags,_latin1'$') as char(20) array),json'["t7", "t8"]')  (cost=45.5 rows=100)
    -> Index range scan on items using idx_tags over ('t8' MEMBER OF (json_extract(tags,_latin1'$'))) OR ('t7' MEMBER OF (json_extract(tags,_latin1'$')))  (cost=45.5 rows=100)

COUNT(*) = 50

Compare the 50,000-row scan with the 50-row estimates above. Two details worth knowing, both seen on this server:

  • The query expression must match the index expression, including the ->'$' path. With the index in place, 't7' MEMBER OF (tags) written against the bare column was still planned as a table scan (Table scan on items, about 50,000 rows).

  • JSON_CONTAINS with a two-element candidate array ('["t7","office"]') was planned as a table scan here, because office matches about a fifth of the rows and the optimizer judged the scan cheaper, while the single-value form used the index. Always check with EXPLAIN rather than assuming an index is used.

Restrictions: a table can have several multi-valued indexes, but a given index may contain only one multi-valued key part; the indexed values are limited in count and size (the server enforces this at write time and returns an error), and a multi-valued index cannot be a primary key or a foreign key, and cannot be covering.

Validating structure with JSON Schema

JSON_SCHEMA_VALID(schema, document) tests a document against a JSON Schema (draft 4 subset), and JSON_SCHEMA_VALIDATION_REPORT explains a failure. As a CHECK constraint it enforces structure that the JSON type alone does not:

SELECT sku, JSON_SCHEMA_VALID('{"type":"object","required":["color"]}', attrs) AS ok FROM products;
SELECT JSON_SCHEMA_VALIDATION_REPORT('{"type":"object","required":["color"]}', attrs)
FROM products WHERE sku='C-3';
sku A-1 ok=1, A-2 ok=1, B-7 ok=1, C-3 ok=0, C-9 ok=0

{"valid": false, "reason": "The JSON document location '#' failed requirement 'required' at JSON Schema location '#'", "schema-location": "#", "document-location": "#", "schema-failed-keyword": "required"}
ALTER TABLE products ADD CONSTRAINT chk_attrs
  CHECK (JSON_SCHEMA_VALID('{"type":"object","properties":{"color":{"type":"string"}}}', attrs));
INSERT INTO products VALUES ('Z-2','x','x',1,1,'[]','{"color": 5}');
ALTER TABLE products DROP CHECK chk_attrs;
ERROR 3819 (HY000): Check constraint 'chk_attrs' is violated.

Limits and good practice

  • A document is limited by max_allowed_packet (67108864 bytes, 64 MiB, on this server) and by the memory the server uses to build it. Very large documents make every full rewrite expensive.

  • Nesting depth is limited (100 levels); JSON_DEPTH reports it.

  • JSON columns cannot have a default value other than an expression, cannot be indexed directly, and have no collation (comparison is by JSON rules, strings by utf8mb4_bin).

  • Large documents are stored off-page (like BLOB), so selecting the column is far costlier than selecting a scalar; extract only the paths you need, or promote hot paths to real columns.

  • Use real columns for data that is relational (keys, amounts, statuses). Use JSON for sparse or evolving attributes such as the product attributes here, and index the few paths you filter on.

  • Joins and foreign keys cannot target a JSON path; an index on the path (above) is the supported way to join or look up by an embedded value.

For tooling and migrating between document and relational designs see MongoDB, and for planning a model see Choosing the right database. Related MySQL pages: Data Types & MySQL-specific SQL, Indexing, Query Planning & EXPLAIN and the MySQL Reference.