SQL reference (MySQL and MariaDB dialects)

JSON type

The JSON column type in the MySQL and MariaDB dialects: validation, storage as text, paths and the differences from the servers.

Syntax#

SQL
column_name JSON [NOT NULL] [DEFAULT ...]

Remarks#

  • Validation. A value written into a JSON column must be valid JSON. If it is not, the statement fails with error 3140 (JSON parse problem "..." at position n while storing a value for column 't.j'.), with MySQL's words for the fault: The document is empty., Missing a name for object member., Missing a comma or ']' after an array element., and so on. For example {bad, the empty text, [1, 2, {"a" 1}, {"a": 1 "b": 2}, [1, 2] x, abc, "abc and [1,] all give MySQL 9.7's text.
  • Storage. Raft DB keeps the document as the text it was given (the text is checked, not rewritten). MySQL converts it to a binary form and reorders the members of objects; MariaDB's JSON is an alias of LONGTEXT with a validity check, which is closer to Raft DB.
  • SHOW CREATE TABLE and DESCRIBE show the type as json.
  • Functions. See JSON functions. Paths use $, .key, [n], [last], [a to b], .*, [*] and **. CAST(x AS JSON) marks a value as a document.
  • Operators. ->, ->> and MEMBER OF in the MySQL dialect; see JSON operators.
  • Indexes. Functional indexes and generated columns over a JSON expression are covered on CREATE TABLE statement.
  • Aggregate. JSON_ARRAYAGG builds an array from the rows of a group.
  • Invalid text from other places. In a function call a text that is not JSON gives error 3141 in the MySQL dialect and NULL in the MariaDB dialect.

Examples#

SQL
CREATE TABLE j (id INT PRIMARY KEY, d JSON);
INSERT INTO j VALUES (1, '{"a": 1, "b": "x", "c": [1, 2, 3], "n": {"k": "v"}}'), (2, '{"a": 2, "b": "y"}');
SELECT id, d->'$.a', d->>'$.b', d->'$.c[1]', d->>'$.n.k' FROM j;       -- MySQL dialect
SELECT id, JSON_EXTRACT(d, '$.a'), JSON_UNQUOTE(JSON_EXTRACT(d, '$.b')) FROM j;
INSERT INTO j VALUES (3, '{bad');                                      -- error 3140

See also#