Database JSON in Relational Databases
What you will learn
- Why store JSON in a relational table
- How to validate JSON with a
CHECKconstraint - How to extract values with
json_extractand read arrays withjson_each - How to index a JSON field and update part of a document
- When a normal column is the better choice
1. Why JSON in a table?
JSON is a text format for nested data: objects {"a": 1}, lists [1, 2], strings and numbers. Most modern relational databases can store JSON inside a column and query it. This gives you the flexibility of a document database (lesson 9.2) for the odd parts of your data, while keeping tables, keys and constraints for the rest.
It fits data whose shape varies: web event logs, settings, data from an outside service. It fits badly data you search, join and count all the time. For that, normal columns win (section 5).
PostgreSQL's documentation, for example, describes JSON data types for storing JSON data, including a jsonb type; the details differ between systems, so the functions in this lesson are SQLite's and are all run here.
2. Store and validate
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds a small table of its own to your browser's copy; run the examples from top to bottom, and Reset data starts again.
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT CHECK (json_valid(payload)));
INSERT INTO events (payload) VALUES
('{"user": "rina", "type": "login", "device": {"os": "android", "v": 14}}'),
('{"user": "sam", "type": "purchase", "items": [{"sku": "tea", "qty": 2}, {"sku": "rice", "qty": 1}], "total": 440}'),
('{"user": "rina", "type": "purchase", "items": [{"sku": "rice", "qty": 3}], "total": 240}');
SELECT id, payload FROM events ORDER BY id;
id payload
-- -----------------------------------------------------------------------------------------------------------------
1 {"user": "rina", "type": "login", "device": {"os": "android", "v": 14}}
2 {"user": "sam", "type": "purchase", "items": [{"sku": "tea", "qty": 2}, {"sku": "rice", "qty": 1}], "total": 440}
3 {"user": "rina", "type": "purchase", "items": [{"sku": "rice", "qty": 3}], "total": 240}
(3 rows)
A broken document is refused:
INSERT INTO events (payload) VALUES ('{broken');
IntegrityError: CHECK constraint failed: json_valid(payload)
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT CHECK (json_valid(payload)));
INSERT INTO events (payload) VALUES
('{"user": "rina", "type": "login", "device": {"os": "android", "v": 14}}'),
('{"user": "sam", "type": "purchase", "items": [{"sku": "tea", "qty": 2}, {"sku": "rice", "qty": 1}], "total": 440}'),
('{"user": "rina", "type": "purchase", "items": [{"sku": "rice", "qty": 3}], "total": 240}');
SELECT id, payload FROM events ORDER BY id;
id payload
-- -----------------------------------------------------------------------------------------------------------------
1 {"user": "rina", "type": "login", "device": {"os": "android", "v": 14}}
2 {"user": "sam", "type": "purchase", "items": [{"sku": "tea", "qty": 2}, {"sku": "rice", "qty": 1}], "total": 440}
3 {"user": "rina", "type": "purchase", "items": [{"sku": "rice", "qty": 3}], "total": 240}
(3 rows)
A broken document is refused:
INSERT INTO events (payload) VALUES ('{broken');
IntegrityError: CHECK constraint failed: json_valid(payload)
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT CHECK (json_valid(payload)));
INSERT INTO events (payload) VALUES
('{"user": "rina", "type": "login", "device": {"os": "android", "v": 14}}'),
('{"user": "sam", "type": "purchase", "items": [{"sku": "tea", "qty": 2}, {"sku": "rice", "qty": 1}], "total": 440}'),
('{"user": "rina", "type": "purchase", "items": [{"sku": "rice", "qty": 3}], "total": 240}');
SELECT id, payload FROM events ORDER BY id;
id payload
-- -----------------------------------------------------------------------------------------------------------------
1 {"user": "rina", "type": "login", "device": {"os": "android", "v": 14}}
2 {"user": "sam", "type": "purchase", "items": [{"sku": "tea", "qty": 2}, {"sku": "rice", "qty": 1}], "total": 440}
3 {"user": "rina", "type": "purchase", "items": [{"sku": "rice", "qty": 3}], "total": 240}
(3 rows)
A broken document is refused:
INSERT INTO events (payload) VALUES ('{broken');
IntegrityError: CHECK constraint failed: json_valid(payload)
In SQLite, JSON is stored as ordinary text. The CHECK (json_valid(payload)) rule (lesson 2.7) refuses text that is not valid JSON, so a broken document cannot get in. The three events have different shapes: only the login has device, only the purchases have items and total.
3. Pull values out
json_extract(column, path) reads a value. The path starts with $ for the whole document, then .name for a key and [0] for a list position:
SELECT id, json_extract(payload, '$.user') AS user, json_extract(payload, '$.type') AS type FROM events ORDER BY id;
SELECT id, json_extract(payload, '$.device.os') AS device_os FROM events ORDER BY id;
SELECT id, json_extract(payload, '$.total') AS total FROM events WHERE json_extract(payload, '$.type') = 'purchase' ORDER BY id;
id user type
-- ---- --------
1 rina login
2 sam purchase
3 rina purchase
(3 rows)
id device_os
-- ---------
1 android
2 NULL
3 NULL
(3 rows)
id total
-- -----
2 440
3 240
(2 rows)
SELECT id, json_extract(payload, '$.user') AS user, json_extract(payload, '$.type') AS type FROM events ORDER BY id;
SELECT id, json_extract(payload, '$.device.os') AS device_os FROM events ORDER BY id;
SELECT id, json_extract(payload, '$.total') AS total FROM events WHERE json_extract(payload, '$.type') = 'purchase' ORDER BY id;
id user type
-- ---- --------
1 rina login
2 sam purchase
3 rina purchase
(3 rows)
id device_os
-- ---------
1 android
2 NULL
3 NULL
(3 rows)
id total
-- -----
2 440
3 240
(2 rows)
SELECT id, json_extract(payload, '$.user') AS user, json_extract(payload, '$.type') AS type FROM events ORDER BY id;
SELECT id, json_extract(payload, '$.device.os') AS device_os FROM events ORDER BY id;
SELECT id, json_extract(payload, '$.total') AS total FROM events WHERE json_extract(payload, '$.type') = 'purchase' ORDER BY id;
id user type
-- ---- --------
1 rina login
2 sam purchase
3 rina purchase
(3 rows)
id device_os
-- ---------
1 android
2 NULL
3 NULL
(3 rows)
id total
-- -----
2 440
3 240
(2 rows)
Where a key does not exist (the purchases have no device) the result is NULL, not an error (lesson 2.3).
To read a list, json_each turns each element into its own row, which you can join to the event it came from:
SELECT e.id, j.value ->> '$.sku' AS sku, j.value ->> '$.qty' AS qty
FROM events e, json_each(e.payload, '$.items') j
ORDER BY e.id, j.key;
id sku qty
-- ---- ---
2 tea 2
2 rice 1
3 rice 3
(3 rows)
SELECT e.id, j.value ->> '$.sku' AS sku, j.value ->> '$.qty' AS qty
FROM events e, json_each(e.payload, '$.items') j
ORDER BY e.id, j.key;
id sku qty
-- ---- ---
2 tea 2
2 rice 1
3 rice 3
(3 rows)
SELECT e.id, j.value ->> '$.sku' AS sku, j.value ->> '$.qty' AS qty
FROM events e, json_each(e.payload, '$.items') j
ORDER BY e.id, j.key;
id sku qty
-- ---- ---
2 tea 2
2 rice 1
3 rice 3
(3 rows)
The event with id 1 has no items, so it contributes no rows. The ->> operator extracts a value from the JSON element j.value as a plain SQL value.
The sample tables can produce JSON too. json_object builds a document from columns of a row:
SELECT json_object('id', product_id, 'name', name, 'price', price) AS product_json
FROM products ORDER BY product_id LIMIT 3;
product_json
-----------------------------------------------
{"id":1,"name":"Steel pan","price":6.6}
{"id":2,"name":"Ceramic mug","price":44.1}
{"id":3,"name":"Wooden spoon set","price":29.5}
(3 rows)
SELECT json_object('id', customer_id, 'name', full_name, 'city', city) AS customer_json
FROM customers ORDER BY customer_id LIMIT 3;
customer_json
----------------------------------------------
{"id":1,"name":"Chen Park","city":"Lima"}
{"id":2,"name":"Rafi Uddin","city":"Manila"}
{"id":3,"name":"Grace Kamau","city":"Toronto"}
(3 rows)
SELECT json_object('id', student_id, 'name', first_name || ' ' || last_name, 'year', enrolled_year) AS student_json
FROM students ORDER BY student_id LIMIT 3;
student_json
------------------------------------------
{"id":1,"name":"Vera Khan","year":2026}
{"id":2,"name":"Elena Haque","year":2024}
{"id":3,"name":"Chloe Garcia","year":2025}
(3 rows)
4. Index and update
Searching inside JSON would normally scan every row. An index on an expression (lesson 7.4) fixes that:
CREATE INDEX idx_user ON events (json_extract(payload, '$.user'));
EXPLAIN QUERY PLAN SELECT * FROM events WHERE json_extract(payload, '$.user') = 'rina';
plan
---------------------------------------------
SEARCH events USING INDEX idx_user (<expr>=?)
(1 row)
CREATE INDEX idx_user ON events (json_extract(payload, '$.user'));
EXPLAIN QUERY PLAN SELECT * FROM events WHERE json_extract(payload, '$.user') = 'rina';
plan
---------------------------------------------
SEARCH events USING INDEX idx_user (<expr>=?)
(1 row)
CREATE INDEX idx_user ON events (json_extract(payload, '$.user'));
EXPLAIN QUERY PLAN SELECT * FROM events WHERE json_extract(payload, '$.user') = 'rina';
plan
---------------------------------------------
SEARCH events USING INDEX idx_user (<expr>=?)
(1 row)
The plan says SEARCH ... USING INDEX, so the lookup uses the index instead of scanning. The query must use the same expression as the index, or the index is not used.
To change one part of a document, use json_set:
UPDATE events SET payload = json_set(payload, '$.total', 999) WHERE id = 2;
SELECT payload FROM events WHERE id = 2;
payload
---------------------------------------------------------------------------------------------------
{"user":"sam","type":"purchase","items":[{"sku":"tea","qty":2},{"sku":"rice","qty":1}],"total":999}
(1 row)
UPDATE events SET payload = json_set(payload, '$.total', 999) WHERE id = 2;
SELECT payload FROM events WHERE id = 2;
payload
---------------------------------------------------------------------------------------------------
{"user":"sam","type":"purchase","items":[{"sku":"tea","qty":2},{"sku":"rice","qty":1}],"total":999}
(1 row)
UPDATE events SET payload = json_set(payload, '$.total', 999) WHERE id = 2;
SELECT payload FROM events WHERE id = 2;
payload
---------------------------------------------------------------------------------------------------
{"user":"sam","type":"purchase","items":[{"sku":"tea","qty":2},{"sku":"rice","qty":1}],"total":999}
(1 row)
Only total changed. The rest of the document is untouched.
Quick check: what does json_extract return for a key that does not exist?
NULL, not an error.
5. When a plain column is better
Worked example: JSON or columns?
A shop stores orders. Which data goes where?
| Data | Better as | Why |
|---|---|---|
| order total, date, customer id | normal columns | searched, summed, joined and constrained every day |
| each line item (sku, qty, price) | a separate table (lesson 3.4) | counted and joined; needs foreign keys |
| the payment gateway's raw reply, whose shape changes | a JSON column | varies, rarely queried, worth keeping as received |
| per-user display settings | a JSON column | flexible, small, read as a whole |
A useful rule: if you filter, join, sum or enforce rules on a field often, make it a column. Keep JSON for the leftovers. The shop is made up.
Common mistakes
- Putting everything in one JSON column and losing keys, types and constraints (the opposite of chapters 2 and 3).
- Searching inside JSON without an index and wondering why it is slow on a large table.
- Querying with a different expression than the index so the index is never used.
- Assuming every key exists. Missing keys give
NULL; handle it. - Assuming the same JSON functions in every product. Names and operators differ.
Key takeaways
- JSON columns store flexible, nested data inside a relational table.
CHECK (json_valid(...))keeps broken documents out.json_extractreads values,json_eachturns a list into rows,json_setchanges one part.- Index the JSON expression you search by, and use exactly that expression in queries.
- Use normal columns and tables for data you filter, join and constrain; use JSON for the varying leftovers.
Practice
1. What does CHECK (json_valid(payload)) do?
Show answer
It makes the database refuse any row whose payload is not valid JSON.
2. Write the path to the os value inside device in the first event.
Show answer
'$.device.os', used as json_extract(payload, '$.device.os').
3. Why did the json_each query return three rows and not four?
Show answer
Event 2 has two items and event 3 has one, giving three. Event 1 has no items, so it produces no rows.
4. Why must a query use the same expression as the index on json_extract(payload, '$.user')?
Show answer
The index stores the results of that exact expression. A different expression cannot be looked up in it, so the database would scan the table instead.
5. What changes when you run json_set(payload, '$.total', 999)?
Show answer
Only the total value in that document; all other keys stay as they were.
6. Name one field you would keep as a normal column and one you would keep as JSON in an online shop, and say why.
Show answer
For example: the order total as a column (summed and filtered often) and the payment gateway's raw reply as JSON (shape varies and is rarely searched).