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_id | info |
|---|---|
| 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"} |
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') |
|---|---|---|---|
| 1 | 1 | 0 | 0 |
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}');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]} |
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_id | origin | first_size | sizes | hot |
|---|---|---|---|---|
| 1 | Chiang Rai | S | ["S","M","L"] | 1 |
| 2 | Chiang Mai | M | ["M","L"] | 0 |
| 4 | NULL | NULL | NULL | NULL |
| 6 | NULL | NULL | NULL | NULL |
| 9 | Ranong | NULL | NULL | NULL |
| 10 | NULL | NULL | NULL | NULL |
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:
->gives the value as JSON: the text"Chiang Rai", quotes and all.->>gives the value as an SQL value: the textChiang Rai, the number200. This is whatjson_extractgives too.
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_id | arrow | double_arrow | sizes_json | sizes_text |
|---|---|---|---|---|
| 1 | "Chiang Rai" | Chiang Rai | ["S","M","L"] | ["S","M","L"] |
| 2 | "Chiang Mai" | Chiang Mai | ["M","L"] | ["M","L"] |
| 4 | NULL | NULL | NULL | NULL |
| 6 | NULL | NULL | NULL | NULL |
| 9 | "Ranong" | Ranong | NULL | NULL |
| 10 | NULL | NULL | NULL | NULL |
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') |
|---|---|---|---|
| text | integer | text | text |
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;| name | origin |
|---|---|
| Cashew Nuts | Ranong |
| Coffee | Chiang Rai |
| Green Tea | Chiang Mai |
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;| name | shelf_days |
|---|---|
| Croissant | 2 |
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 |
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"]');| key | value | type |
|---|---|---|
| 0 | wheat | text |
| 1 | milk | text |
| 2 | egg | text |
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;| name | allergen |
|---|---|
| Cashew Nuts | nuts |
| Cheesecake | milk |
| Cheesecake | egg |
| Croissant | wheat |
| Croissant | milk |
| Croissant | egg |
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;| name | allergens |
|---|---|
| Cheesecake | 2 |
| Croissant | 3 |
On an object, json_each gives a row for each key:
SELECT key, value FROM json_each('{"pages": 80, "color": "blue"}');| key | value |
|---|---|
| pages | 80 |
| color | blue |
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} |
SELECT json_array(1, 'two', NULL, 4.5), json_array();| json_array(1, 'two', NULL, 4.5) | json_array() |
|---|---|
| [1,"two",null,4.5] | [] |
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;| category | products |
|---|---|
| Drinks | ["Coffee","Green Tea","Orange Juice"] |
| Bakery | ["Croissant","Banana Bread","Cheesecake"] |
| Snacks | ["Potato Chips","Dried Mango","Cashew Nuts"] |
| Stationery | ["Notebook","Pen","Highlighter"] |
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} |
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}]} |
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:
| Function | Key there | Key not there |
|---|---|---|
json_set | changes it | adds it |
json_insert | leaves it | adds it |
json_replace | changes it | leaves it out |
json_remove | removes it | nothing |
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_set | json_insert | json_replace | json_remove |
|---|---|---|---|
| {"a":9,"b":2} | {"a":1,"b":2} | {"a":9} | {"a":1} |
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_id | info |
|---|---|
| 1 | {"origin":"Chiang Rai","roast":"dark","sizes":["S","M","L","XL"],"hot":true} |
| 2 | {"origin":"Chiang Mai","sizes":["M","L"]} |
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.
- Show the name and origin of every product that has an origin, sorted by origin.
- Croissant (id 4) now keeps 3 days. Change its
shelf_daysinproduct_detail, then show its JSON. - Make one JSON array of the names of the products that are out of stock (
stock = 0). - Show each product that has
allergenswith 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;| name | origin |
|---|---|
| Green Tea | Chiang Mai |
| Coffee | Chiang Rai |
| Cashew Nuts | Ranong |
| info |
|---|
| {"allergens":["wheat","milk","egg"],"shelf_days":3} |
| out_of_stock |
|---|
| ["Orange Juice","Highlighter"] |
| name | allergens |
|---|---|
| Croissant | 3 |
| Cheesecake | 2 |
| Cashew Nuts | 1 |
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