TExcelTAD
Home › MySQL › MySQL JSON Functions

MySQL JSON Functions

Sometimes part of your data doesn't fit neatly into fixed columns: product attributes that differ per category, user preferences, the raw payload of a web hook. MySQL lets you store such data as JSON and query into it with SQL functions.

The JSON type

sql
CREATE TABLE product_attrs (
  product_id INT PRIMARY KEY,
  attrs      JSON NOT NULL
);

A JSON column only accepts valid JSON documents; invalid text is rejected on insert.

MySQL vs MariaDB: MySQL stores JSON in a binary format and normalises documents (it removes extra spaces and may reorder object keys), so SELECT attrs shows a reformatted document. MariaDB stores JSON as LONGTEXT with a validity check and keeps the text exactly as inserted. The examples below therefore print values extracted from documents, which are the same on both. MySQL's CAST(text AS JSON) and the shorthand operators -> and ->> (below) don't exist in MariaDB.

Every example starts with this small table:

sql
CREATE TABLE product_attrs (product_id INT PRIMARY KEY, attrs JSON NOT NULL);
INSERT INTO product_attrs VALUES
 (1,  '{"origin": "Colombia", "roast": "dark", "organic": true, "awards": ["Gold 2023", "Silver 2024"]}'),
 (2,  '{"origin": "India", "organic": false, "caffeine_mg": 40}'),
 (10, '{"origin": "Switzerland", "aged_months": 12, "milk": {"type": "cow", "raw": true}}');

Extracting values

A path addresses a part of a document: $ is the whole document, $.origin a key, $.awards[0] the first array element, $.milk.type a nested key.

Function Returns
JSON_EXTRACT(doc, path) the JSON value at the path (strings keep their quotes)
JSON_UNQUOTE(json) a JSON string as plain text
JSON_VALUE(doc, path) the scalar at the path as plain text (MySQL 8.0.21+, MariaDB 10.2+)
mysql · try it yourself
CREATE TABLE product_attrs (product_id INT PRIMARY KEY, attrs JSON NOT NULL);
INSERT INTO product_attrs VALUES
 (1,  '{"origin": "Colombia", "roast": "dark", "organic": true, "awards": ["Gold 2023", "Silver 2024"]}'),
 (2,  '{"origin": "India", "organic": false, "caffeine_mg": 40}'),
 (10, '{"origin": "Switzerland", "aged_months": 12, "milk": {"type": "cow", "raw": true}}');

SELECT product_id,
       JSON_EXTRACT(attrs, '$.origin') AS extracted,
       JSON_UNQUOTE(JSON_EXTRACT(attrs, '$.origin')) AS origin,
       JSON_VALUE(attrs, '$.awards[0]') AS first_award,
       JSON_VALUE(attrs, '$.milk.type') AS milk
FROM product_attrs;
+------------+---------------+-------------+-------------+------+
| product_id | extracted     | origin      | first_award | milk |
+------------+---------------+-------------+-------------+------+
|          1 | "Colombia"    | Colombia    | Gold 2023   | NULL |
|          2 | "India"       | India       | NULL        | NULL |
|         10 | "Switzerland" | Switzerland | NULL        | cow  |
+------------+---------------+-------------+-------------+------+

Missing paths give NULL, not an error. In MySQL you can write the same extractions more briefly:

sql
SELECT attrs->'$.origin',      -- JSON_EXTRACT(attrs, '$.origin')        -> "Colombia"
       attrs->>'$.origin'      -- JSON_UNQUOTE(JSON_EXTRACT(...))        -> Colombia
FROM product_attrs;

Filtering on JSON

Extracted values can be used in WHERE, joins and ORDER BY like any other expression. To test a JSON boolean, compare JSON with JSON: JSON_CONTAINS(doc, 'true', path) checks that the value at path is the JSON literal true:

mysql · try it yourself
CREATE TABLE product_attrs (product_id INT PRIMARY KEY, attrs JSON NOT NULL);
INSERT INTO product_attrs VALUES
 (1,  '{"origin": "Colombia", "roast": "dark", "organic": true, "awards": ["Gold 2023", "Silver 2024"]}'),
 (2,  '{"origin": "India", "organic": false, "caffeine_mg": 40}'),
 (10, '{"origin": "Switzerland", "aged_months": 12, "milk": {"type": "cow", "raw": true}}');

SELECT p.name, JSON_VALUE(a.attrs, '$.origin') AS origin
FROM product_attrs AS a
JOIN products AS p ON p.product_id = a.product_id
WHERE JSON_CONTAINS(a.attrs, 'true', '$.organic')
   OR JSON_VALUE(a.attrs, '$.aged_months') >= 12
ORDER BY p.name;
+--------------------+-------------+
| name               | origin      |
+--------------------+-------------+
| Aged Gruyere 250g  | Switzerland |
| Espresso Beans 1kg | Colombia    |
+--------------------+-------------+

Inspecting documents

Function Returns
JSON_VALID(text) 1 if the text is valid JSON
JSON_TYPE(json) OBJECT, ARRAY, STRING, INTEGER, BOOLEAN, …
JSON_LENGTH(doc [, path]) number of elements of an array/object
JSON_CONTAINS_PATH(doc, 'one', path...) 1 if the path exists
JSON_CONTAINS(target, candidate) 1 if candidate is contained in target
JSON_SEARCH(doc, 'one', str) the path of the first matching string
mysql · try it yourself
CREATE TABLE product_attrs (product_id INT PRIMARY KEY, attrs JSON NOT NULL);
INSERT INTO product_attrs VALUES
 (1,  '{"origin": "Colombia", "roast": "dark", "organic": true, "awards": ["Gold 2023", "Silver 2024"]}'),
 (2,  '{"origin": "India", "organic": false, "caffeine_mg": 40}'),
 (10, '{"origin": "Switzerland", "aged_months": 12, "milk": {"type": "cow", "raw": true}}');

SELECT product_id,
       JSON_LENGTH(attrs) AS top_level_keys,
       JSON_LENGTH(attrs, '$.awards') AS awards,
       JSON_CONTAINS_PATH(attrs, 'one', '$.milk') AS has_milk,
       JSON_CONTAINS(JSON_EXTRACT(attrs, '$.awards'), '"Gold 2023"') AS won_gold,
       JSON_UNQUOTE(JSON_SEARCH(attrs, 'one', 'dark')) AS path_of_dark
FROM product_attrs
ORDER BY product_id;

SELECT JSON_VALID('{"a": 1}') AS good, JSON_VALID('{a: 1}') AS bad,
       JSON_TYPE('[1, 2]') AS arr, JSON_TYPE('"x"') AS str;
+------------+----------------+--------+----------+----------+--------------+
| product_id | top_level_keys | awards | has_milk | won_gold | path_of_dark |
+------------+----------------+--------+----------+----------+--------------+
|          1 |              4 |      2 |        0 |        1 | $.roast      |
|          2 |              3 |   NULL |        0 |     NULL | NULL         |
|         10 |              3 |   NULL |        1 |     NULL | NULL         |
+------------+----------------+--------+----------+----------+--------------+
+------+------+-------+--------+
| good | bad  | arr   | str    |
+------+------+-------+--------+
|    1 |    0 | ARRAY | STRING |
+------+------+-------+--------+

Changing documents

JSON_SET inserts or replaces values, JSON_INSERT only adds missing ones, JSON_REPLACE only changes existing ones, and JSON_REMOVE deletes paths. They return a new document, so use them in UPDATE ... SET col = JSON_SET(col, ...):

mysql · try it yourself
CREATE TABLE product_attrs (product_id INT PRIMARY KEY, attrs JSON NOT NULL);
INSERT INTO product_attrs VALUES
 (2,  '{"origin": "India", "organic": false, "caffeine_mg": 40}');

UPDATE product_attrs
SET attrs = JSON_SET(attrs, '$.organic', TRUE, '$.grade', 'FTGFOP')
WHERE product_id = 2;
UPDATE product_attrs SET attrs = JSON_REMOVE(attrs, '$.caffeine_mg') WHERE product_id = 2;
UPDATE product_attrs SET attrs = JSON_INSERT(attrs, '$.origin', 'Kenya') WHERE product_id = 2;

SELECT JSON_EXTRACT(attrs, '$.organic') AS organic,
       JSON_VALUE(attrs, '$.grade') AS grade,
       JSON_VALUE(attrs, '$.origin') AS origin,
       JSON_CONTAINS_PATH(attrs, 'one', '$.caffeine_mg') AS has_caffeine,
       JSON_LENGTH(attrs) AS keys_now
FROM product_attrs;
+---------+--------+--------+--------------+----------+
| organic | grade  | origin | has_caffeine | keys_now |
+---------+--------+--------+--------------+----------+
| true    | FTGFOP | India  |            0 |        3 |
+---------+--------+--------+--------------+----------+

JSON_INSERT left origin alone because the key already existed.

Building JSON from rows

JSON_OBJECT and JSON_ARRAY build documents from values, which is handy for APIs that want JSON straight from the database:

mysql · try it yourself
SELECT JSON_OBJECT('id', product_id, 'name', name) AS product_json,
       JSON_ARRAY(product_id, name, NULL) AS as_array
FROM products
WHERE product_id IN (5, 8);
+-------------------------------------+-----------------------------+
| product_json                        | as_array                    |
+-------------------------------------+-----------------------------+
| {"id": 5, "name": "Sourdough Loaf"} | [5, "Sourdough Loaf", null] |
| {"id": 8, "name": "Rye Crackers"}   | [8, "Rye Crackers", null]   |
+-------------------------------------+-----------------------------+

The aggregate versions JSON_ARRAYAGG(expr) and JSON_OBJECTAGG(key, value) collect a whole group into one array or object (MySQL prints [1, 2, 3], MariaDB [1,2,3]).

JSON_TABLE: from JSON back to rows

JSON_TABLE turns a JSON array into a relational table you can join and filter (MySQL 8.0.4+, MariaDB 10.6+):

mysql · try it yourself
SELECT jt.*
FROM JSON_TABLE(
  '[{"sku": "A-1", "qty": 3}, {"sku": "B-7", "qty": 1}, {"sku": "C-2", "qty": 12}]',
  '$[*]' COLUMNS (
      line FOR ORDINALITY,
      sku  VARCHAR(10) PATH '$.sku',
      qty  INT         PATH '$.qty'
  )
) AS jt
WHERE jt.qty > 1;
+------+------+------+
| line | sku  | qty  |
+------+------+------+
|    1 | A-1  |    3 |
|    3 | C-2  |   12 |
+------+------+------+

Tip: JSON is great for truly variable data, but values you filter, join or constrain often belong in real columns: they get proper types, constraints and ordinary indexes. In MySQL you can index a JSON value through a generated column: ALTER TABLE product_attrs ADD origin VARCHAR(40) AS (attrs->>'$.origin'), ADD INDEX (origin);.

Test yourself

Which path selects the second element of the array under key tags?

  1. $.tags[2]
  2. $.tags[1]
  3. $tags.1
  4. tags[1]

What is the difference between JSON_EXTRACT(doc, '$.name') and JSON_UNQUOTE(JSON_EXTRACT(doc, '$.name'))?

  1. None
  2. The first returns a JSON string with quotes, the second plain text
  3. The second returns NULL for strings
  4. The first only works on arrays

Which function adds a key only if it doesn't exist yet?

  1. JSON_SET
  2. JSON_REPLACE
  3. JSON_INSERT
  4. JSON_MERGE