Reading history

SQL JSON Functions: Query JSON Data with Examples

6 min read 0 views

Query JSON in SQL: json_extract and the ->> operator, JSON paths, filtering on JSON fields, json_each for arrays, json_group_array and json_set, with PostgreSQL and MySQL equivalents.

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_extract and the ->> operator
  • JSON paths such as $.device.os and $.items[0]
  • Filtering and aggregating on JSON fields
  • Turning arrays into rows with json_each
  • Building and changing JSON with json_object, json_group_array and json_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 data column. Different events have different fields: logins have a device, purchases have amount and items.
  • A JSON path starts with $ (the whole document). $.user is a top-level key, $.device.os goes one level deeper, and $.items[0] is the first element of an array.
  • json_extract(data, path) and the shorter data ->> path both 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 BY and SUM. 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_each is a table-valued function: it returns one row per array element, with columns such as key (the position) and value. Joining it to the table “unnests” each purchase into its items.
  • json_object builds an object from key/value pairs, and the aggregate json_group_array collects 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; the UPDATE stores it back. json_valid returns 1 for well-formed JSON.

JSON Across Databases

TaskSQLitePostgreSQL (jsonb)MySQL
Get a value as textdata ->> '$.user'data ->> 'user'data ->> '$.user'
Nested value'$.device.os'data #>> '{device,os}''$.device.os'
Array to rowsjson_eachjsonb_array_elementsJSON_TABLE
Rows to arrayjson_group_arrayjsonb_aggJSON_ARRAYAGG
Change a valuejson_setjsonb_setJSON_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

  1. Putting everything in JSON. Fields you filter, join or validate on regularly belong in real columns with types and constraints.
  2. Confusing -> and ->>. -> returns JSON (strings keep their quotes); ->> returns a plain SQL value.
  3. Forgetting that a missing key returns NULL, which can silently drop rows from a filter.
  4. 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 .key and [index].
  • ->> and json_extract pull out plain values for filtering and grouping.
  • json_each turns arrays into rows; json_group_array does the reverse.
  • Keep frequently queried fields in real columns.

Next: SQL Pagination: LIMIT/OFFSET vs Keyset.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *