32. JSON in a column

Keep details that differ from row to row as JSON text, then read, search, build and change it with SQL.

Why JSON in a database

Our products are all different. Coffee has an origin and cup sizes, a croissant has allergens and a shelf life, a notebook has a number of pages. Giving product a column for every detail of every kind of product would make a wide table that is mostly NULL.

One answer is to keep those details as JSON, the text format web programs use to send data: {"key": value, ...} for an object, [a, b, c] for an array. To SQLite, JSON is just text in a TEXT column, but the json_... functions can read inside it.

Let's make a table of our own, one row of details for some of the products. CHECK (json_valid(info)) makes sure only real JSON can go in (more on that below):

CREATE TABLE product_detail (
  product_id INTEGER PRIMARY KEY REFERENCES product(id),
  info       TEXT NOT NULL CHECK (json_valid(info))
);

INSERT INTO product_detail (product_id, info) VALUES
  (1,  '{"origin": "Chiang Rai", "roast": "medium", "sizes": ["S", "M", "L"], "hot": true}'),
  (2,  '{"origin": "Chiang Mai", "sizes": ["M", "L"], "hot": false}'),
  (4,  '{"allergens": ["wheat", "milk", "egg"], "shelf_days": 2}'),
  (6,  '{"allergens": ["milk", "egg"], "shelf_days": 4}'),
  (9,  '{"origin": "Ranong", "allergens": ["nuts"], "weight_g": 200}'),
  (10, '{"pages": 80, "color": "blue"}');

SELECT * FROM product_detail;
product_idinfo
1{"origin": "Chiang Rai", "roast": "medium", "sizes": ["S", "M", "L"], "hot": true}
2{"origin": "Chiang Mai", "sizes": ["M", "L"], "hot": false}
4{"allergens": ["wheat", "milk", "egg"], "shelf_days": 2}
6{"allergens": ["milk", "egg"], "shelf_days": 4}
9{"origin": "Ranong", "allergens": ["nuts"], "weight_g": 200}
10{"pages": 80, "color": "blue"}
6 rows

json_valid() and json()

json_valid(x) gives 1 if x is correct JSON and 0 if not. JSON is strict: keys must be in double quotes, so {a: 1} is not JSON, and neither is a bare word:

SELECT json_valid('{"a": 1}'), json_valid('[1, 2, 3]'), json_valid('{a: 1}'), json_valid('hello');
json_valid('{"a": 1}')json_valid('[1, 2, 3]')json_valid('{a: 1}')json_valid('hello')
1100
1 row

That is why the table has CHECK (json_valid(info)): broken JSON is refused at the door, instead of being found months later:

INSERT INTO product_detail (product_id, info) VALUES (3, '{origin: Rayong}');
Error: CHECK constraint failed: json_valid(info)

json(x) checks the JSON and gives it back in its shortest form, the spaces taken out:

SELECT json(' { "a" : 1 ,  "b" : [ 1 , 2 ] } ');
json(' { "a" : 1 , "b" : [ 1 , 2 ] } ')
{"a":1,"b":[1,2]}
1 row

Reading a value: json_extract, -> and ->>

The place of a value inside JSON is written as a path: $ is the whole document, $.origin the key origin, $.sizes[0] the first item of the array sizes (arrays count from 0). json_extract(json, path) gives the value there:

SELECT product_id,
       json_extract(info, '$.origin')   AS origin,
       json_extract(info, '$.sizes[0]') AS first_size,
       json_extract(info, '$.sizes')    AS sizes,
       json_extract(info, '$.hot')      AS hot
FROM product_detail
ORDER BY product_id;
product_idoriginfirst_sizesizeshot
1Chiang RaiS["S","M","L"]1
2Chiang MaiM["M","L"]0
4NULLNULLNULLNULL
6NULLNULLNULLNULL
9RanongNULLNULLNULL
10NULLNULLNULLNULL
6 rows

A key that isn't there gives NULL, no error, so products without an origin simply have NULL. JSON's true and false come out as 1 and 0, and an array or object comes out as JSON text.

There are two shorter ways to write it, the arrows, and they differ in what they give back:

After an arrow you can write the full path '$.origin' or just the key 'origin':

SELECT product_id,
       info -> '$.origin'  AS arrow,
       info ->> '$.origin' AS double_arrow,
       info -> 'sizes'     AS sizes_json,
       info ->> 'sizes'    AS sizes_text
FROM product_detail
ORDER BY product_id;
product_idarrowdouble_arrowsizes_jsonsizes_text
1"Chiang Rai"Chiang Rai["S","M","L"]["S","M","L"]
2"Chiang Mai"Chiang Mai["M","L"]["M","L"]
4NULLNULLNULLNULL
6NULLNULLNULLNULL
9"Ranong"RanongNULLNULL
10NULLNULLNULLNULL
6 rows

See the quotes around "Chiang Rai" in the -> column. For arrays and objects both arrows give the same JSON text. typeof shows the difference plainly: weight_g through -> is text, through ->> a real number:

SELECT typeof(info -> '$.weight_g'), typeof(info ->> '$.weight_g'), typeof(info -> '$.origin'), typeof(info ->> '$.origin')
FROM product_detail WHERE product_id = 9;
typeof(info -> '$.weight_g')typeof(info ->> '$.weight_g')typeof(info -> '$.origin')typeof(info ->> '$.origin')
textintegertexttext
1 row

Use ->> when you want to show, compare or calculate with a value. Use -> when you want to pass a piece of JSON on, into another JSON function or out to a program that reads JSON.

Searching by a value inside JSON

A JSON value works in WHERE like any column. The products that have an origin:

SELECT p.name, d.info ->> 'origin' AS origin
FROM product AS p JOIN product_detail AS d ON d.product_id = p.id
WHERE d.info ->> 'origin' IS NOT NULL
ORDER BY p.name;
nameorigin
Cashew NutsRanong
CoffeeChiang Rai
Green TeaChiang Mai
3 rows

What keeps fewer than 3 days? ->> gives a number, so the comparison is a comparison of numbers:

SELECT p.name, d.info ->> 'shelf_days' AS shelf_days
FROM product AS p JOIN product_detail AS d ON d.product_id = p.id
WHERE d.info ->> 'shelf_days' < 3;
nameshelf_days
Croissant2
1 row

Compare with ->>, not ->. info -> 'shelf_days' is the JSON text 2, and in SQLite any text is greater than any number, so info -> 'shelf_days' < 3 is never true and finds nothing:

SELECT count(*) FROM product_detail WHERE info -> 'shelf_days' < 3;
count(*)
0
1 row

json_each: an array as rows

An array inside one row is awkward to search. json_each(json) turns it into rows, one row per item, with columns key (its place, from 0), value and type:

SELECT key, value, type FROM json_each('["wheat", "milk", "egg"]');
keyvaluetype
0wheattext
1milktext
2eggtext
3 rows

json_each is used in FROM like a table. Give it a path as its second argument to go into an array inside the document, and join it to each row: every product with each of its allergens on a line of its own:

SELECT p.name, a.value AS allergen
FROM product AS p
JOIN product_detail AS d ON d.product_id = p.id
JOIN json_each(d.info, '$.allergens') AS a
ORDER BY p.name, a.key;
nameallergen
Cashew Nutsnuts
Cheesecakemilk
Cheesecakeegg
Croissantwheat
Croissantmilk
Croissantegg
6 rows

6 rows: Croissant has 3 allergens, Cheesecake 2, Cashew Nuts 1. Products with no allergens give no rows. Now "which products have milk in them?" is an EXISTS (chapter 13); json_array_length counts the items of an array:

SELECT p.name, json_array_length(d.info, '$.allergens') AS allergens
FROM product AS p JOIN product_detail AS d ON d.product_id = p.id
WHERE EXISTS (SELECT 1 FROM json_each(d.info, '$.allergens') WHERE value = 'milk')
ORDER BY p.name;
nameallergens
Cheesecake2
Croissant3
2 rows

On an object, json_each gives a row for each key:

SELECT key, value FROM json_each('{"pages": 80, "color": "blue"}');
keyvalue
pages80
colorblue
2 rows

Building JSON from tables

The other way round: programs and web pages often want JSON, and SQL can build it straight from the tables.

json_object(key, value, key, value, ...) builds an object, json_array(...) an array:

SELECT json_object('id', id, 'name', name, 'price', price) AS product_json
FROM product
WHERE category_id = 1
ORDER BY id;
product_json
{"id":1,"name":"Coffee","price":55.0}
{"id":2,"name":"Green Tea","price":45.0}
{"id":3,"name":"Orange Juice","price":40.0}
3 rows
SELECT json_array(1, 'two', NULL, 4.5), json_array();
json_array(1, 'two', NULL, 4.5)json_array()
[1,"two",null,4.5][]
1 row

json_group_array(x) is an aggregate like count (chapter 9): it gathers the x of every row of a group into one array. json_group_object(key, value) gathers them into one object:

SELECT c.name AS category, json_group_array(p.name) AS products
FROM category AS c JOIN product AS p ON p.category_id = c.id
GROUP BY c.id
ORDER BY c.id;
categoryproducts
Drinks["Coffee","Green Tea","Orange Juice"]
Bakery["Croissant","Banana Bread","Cheesecake"]
Snacks["Potato Chips","Dried Mango","Cashew Nuts"]
Stationery["Notebook","Pen","Highlighter"]
4 rows
SELECT json_group_object(name, price) AS prices
FROM product
WHERE category_id = 2;
prices
{"Croissant":35.0,"Banana Bread":60.0,"Cheesecake":120.0}
1 row

They nest: JSON made by one JSON function goes into another as JSON, not as quoted text. One document for a whole category, with its products inside:

SELECT json_object(
         'category', c.name,
         'products', json_group_array(json_object('name', p.name, 'price', p.price))
       ) AS doc
FROM category AS c JOIN product AS p ON p.category_id = c.id
WHERE c.id = 4
GROUP BY c.id;
doc
{"category":"Stationery","products":[{"name":"Notebook","price":30.0},{"name":"Pen","price":15.0},{"name":"Highlighter","price":25.0}]}
1 row

Changing JSON: json_set, json_insert, json_replace, json_remove

These four functions take JSON and a path and give back new JSON; they don't change anything by themselves. They differ in what they do when the key is there or not:

FunctionKey thereKey not there
json_setchanges itadds it
json_insertleaves itadds it
json_replacechanges itleaves it out
json_removeremoves itnothing

Each with a there and b not:

SELECT json_set('{"a": 1}', '$.a', 9, '$.b', 2)     AS json_set,
       json_insert('{"a": 1}', '$.a', 9, '$.b', 2)  AS json_insert,
       json_replace('{"a": 1}', '$.a', 9, '$.b', 2) AS json_replace,
       json_remove('{"a": 1, "b": 2}', '$.b')       AS json_remove;
json_setjson_insertjson_replacejson_remove
{"a":9,"b":2}{"a":1,"b":2}{"a":9}{"a":1}
1 row

To change the JSON in the table, put the result back with UPDATE. Coffee gets a dark roast and an XL size ([#] means "after the last item", so the item is added to the end of the array); Green Tea loses its hot:

UPDATE product_detail
SET info = json_set(info, '$.roast', 'dark', '$.sizes[#]', 'XL')
WHERE product_id = 1;

UPDATE product_detail
SET info = json_remove(info, '$.hot')
WHERE product_id = 2;

SELECT product_id, info FROM product_detail WHERE product_id IN (1, 2);
product_idinfo
1{"origin":"Chiang Rai","roast":"dark","sizes":["S","M","L","XL"],"hot":true}
2{"origin":"Chiang Mai","sizes":["M","L"]}
2 rows

The JSON comes back in its short form, without the spaces we typed.

JSON suits details that differ from row to row and that you rarely search by. Whatever every row has, and whatever you join, sort or search by often (a price, a category, a date), belongs in ordinary columns, where types, constraints, foreign keys and indexes can look after it.

  1. Show the name and origin of every product that has an origin, sorted by origin.
  2. Croissant (id 4) now keeps 3 days. Change its shelf_days in product_detail, then show its JSON.
  3. Make one JSON array of the names of the products that are out of stock (stock = 0).
  4. Show each product that has allergens with how many it has, most first.
Show the answer
SELECT p.name, d.info ->> 'origin' AS origin
FROM product AS p JOIN product_detail AS d ON d.product_id = p.id
WHERE d.info ->> 'origin' IS NOT NULL
ORDER BY origin;

UPDATE product_detail SET info = json_set(info, '$.shelf_days', 3) WHERE product_id = 4;
SELECT info FROM product_detail WHERE product_id = 4;

SELECT json_group_array(name) AS out_of_stock FROM product WHERE stock = 0;

SELECT p.name, json_array_length(d.info, '$.allergens') AS allergens
FROM product AS p JOIN product_detail AS d ON d.product_id = p.id
WHERE d.info -> 'allergens' IS NOT NULL
ORDER BY allergens DESC, p.name;
nameorigin
Green TeaChiang Mai
CoffeeChiang Rai
Cashew NutsRanong
3 rows
info
{"allergens":["wheat","milk","egg"],"shelf_days":3}
1 row
out_of_stock
["Orange Juice","Highlighter"]
1 row
nameallergens
Croissant3
Cheesecake2
Cashew Nuts1
3 rows

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made