Modern applications produce a lot of JSON: API responses, app event logs, settings and form answers whose fields change from one record to the next. Relational databases can now store JSON in a column and query inside it, so you can filter, group and join on a field buried in a document. This lesson shows the core JSON functions with SQLite, whose syntax is very close to PostgreSQL and MySQL.
In this lesson you will learn
- Reading values with
json_extractand the->>operator - JSON paths such as
$.device.osand$.items[0] - Filtering and aggregating on JSON fields
- Turning arrays into rows with
json_each - Building and changing JSON with
json_object,json_group_arrayandjson_set
You should know GROUP BY and joins.
Reading JSON Values
CREATE TABLE app_events (id INTEGER PRIMARY KEY, data TEXT);
INSERT INTO app_events (data) VALUES
('{"user": "nusrat", "action": "login", "device": {"os": "Android", "version": 14}}'),
('{"user": "arif", "action": "purchase", "amount": 450, "items": ["pen", "notebook"]}'),
('{"user": "nusrat", "action": "purchase", "amount": 1200, "items": ["calculator"]}'),
('{"user": "tania", "action": "login", "device": {"os": "iOS", "version": 18}}');
-- Read values out of a JSON document
SELECT id,
json_extract(data, '$.user') AS user,
data ->> '$.action' AS action,
data ->> '$.device.os' AS os,
data ->> '$.items[0]' AS first_item
FROM app_events;
-- Filter and aggregate on JSON fields like ordinary columns
SELECT data ->> '$.user' AS user,
COUNT(*) AS purchases,
SUM(data ->> '$.amount') AS spent
FROM app_events
WHERE data ->> '$.action' = 'purchase'
GROUP BY user
ORDER BY spent DESC;
Output
+----+--------+----------+---------+------------+
| id | user | action | os | first_item |
+----+--------+----------+---------+------------+
| 1 | nusrat | login | Android | NULL |
| 2 | arif | purchase | NULL | pen |
| 3 | nusrat | purchase | NULL | calculator |
| 4 | tania | login | iOS | NULL |
+----+--------+----------+---------+------------+
(4 rows)
+--------+-----------+-------+
| user | purchases | spent |
+--------+-----------+-------+
| nusrat | 1 | 1200 |
| arif | 1 | 450 |
+--------+-----------+-------+
(2 rows)
- Each event is stored as JSON text in the
datacolumn. Different events have different fields: logins have adevice, purchases haveamountanditems. - A JSON path starts with
$(the whole document).$.useris a top-level key,$.device.osgoes one level deeper, and$.items[0]is the first element of an array. json_extract(data, path)and the shorterdata ->> pathboth return the value as a normal SQL value (text or number). A missing path gives NULL rather than an error.- Once extracted, a JSON value works like any column in
WHERE,GROUP BYandSUM. Nusrat made one purchase of 1200 taka.
Arrays, Building and Updating JSON
CREATE TABLE app_events (id INTEGER PRIMARY KEY, data TEXT);
INSERT INTO app_events (data) VALUES
('{"user": "arif", "action": "purchase", "amount": 450, "items": ["pen", "notebook"]}'),
('{"user": "nusrat", "action": "purchase", "amount": 1200, "items": ["calculator"]}');
-- json_each turns a JSON array into rows
SELECT e.id, e.data ->> '$.user' AS user, item.value AS item
FROM app_events e, json_each(e.data, '$.items') AS item
ORDER BY e.id, item.key;
-- Build JSON from table rows
SELECT json_object('dept', dept, 'students', json_group_array(name)) AS dept_json
FROM students
WHERE dept IN ('EEE', 'BBA')
GROUP BY dept
ORDER BY dept;
-- Change a value inside a document
UPDATE app_events SET data = json_set(data, '$.amount', 500) WHERE id = 1;
SELECT id, data ->> '$.amount' AS amount, json_valid(data) AS valid FROM app_events;
Output
+----+--------+------------+
| id | user | item |
+----+--------+------------+
| 1 | arif | pen |
| 1 | arif | notebook |
| 2 | nusrat | calculator |
+----+--------+------------+
(3 rows)
+----------------------------------------------+
| dept_json |
+----------------------------------------------+
| {"dept":"BBA","students":["Imran","Sabbir"]} |
| {"dept":"EEE","students":["Arif","Rafi"]} |
+----------------------------------------------+
(2 rows)
+----+--------+-------+
| id | amount | valid |
+----+--------+-------+
| 1 | 500 | 1 |
| 2 | 1200 | 1 |
+----+--------+-------+
(2 rows)
json_eachis a table-valued function: it returns one row per array element, with columns such askey(the position) andvalue. Joining it to the table “unnests” each purchase into its items.json_objectbuilds an object from key/value pairs, and the aggregatejson_group_arraycollects a group’s values into an array. Together they turn table rows into API-ready JSON.json_set(doc, path, value)returns a copy of the document with one value changed or added; theUPDATEstores it back.json_validreturns 1 for well-formed JSON.
JSON Across Databases
| Task | SQLite | PostgreSQL (jsonb) | MySQL |
|---|---|---|---|
| Get a value as text | data ->> '$.user' | data ->> 'user' | data ->> '$.user' |
| Nested value | '$.device.os' | data #>> '{device,os}' | '$.device.os' |
| Array to rows | json_each | jsonb_array_elements | JSON_TABLE |
| Rows to array | json_group_array | jsonb_agg | JSON_ARRAYAGG |
| Change a value | json_set | jsonb_set | JSON_SET |
PostgreSQL’s jsonb type stores JSON in a parsed binary form and supports GIN indexes for fast searches inside documents. SQL Server uses JSON_VALUE, OPENJSON and FOR JSON.
Common Mistakes
- Putting everything in JSON. Fields you filter, join or validate on regularly belong in real columns with types and constraints.
- Confusing
->and->>.->returns JSON (strings keep their quotes);->>returns a plain SQL value. - Forgetting that a missing key returns NULL, which can silently drop rows from a filter.
- Searching inside JSON on large tables without an index. Index an expression such as
(data ->> '$.user')or a generated column.
Practice Exercises
Exercise 1. Count login events per operating system.
Show answer
SELECT data ->> '$.device.os' AS os, COUNT(*) AS logins
FROM app_events
WHERE data ->> '$.action' = 'login'
GROUP BY os;
Exercise 2. Return each purchase with the number of items it contains.
Show answer
SELECT id, data ->> '$.user' AS user,
json_array_length(data, '$.items') AS items
FROM app_events
WHERE data ->> '$.action' = 'purchase';
On the first example’s data this gives 2 items for Arif and 1 for Nusrat.
Frequently Asked Questions
Should I use a JSON column or a separate table?
Use separate tables and columns for data with a fixed structure that you query often. Use JSON for flexible, rarely filtered details such as user preferences, raw API payloads or optional attributes that differ between rows.
Does SQLite have a JSON data type?
No. SQLite stores JSON as ordinary text (or as binary JSONB from version 3.45), and the JSON functions parse it. Add CHECK (json_valid(data)) to reject invalid documents.
Summary
- JSON paths start at
$and use.keyand[index]. ->>andjson_extractpull out plain values for filtering and grouping.json_eachturns arrays into rows;json_group_arraydoes the reverse.- Keep frequently queried fields in real columns.
