Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');sql
SELECT e.id, t.value AS tag
FROM events e JOIN json_each(e.payload, '$.tags') t
ORDER BY e.id, t.key;| id | tag |
|---|---|
| 1 | web |
| 1 | promo |
| 2 | app |
Event 3 has no tags array, so the join produces nothing for it. A LEFT JOIN keeps it with a NULL tag:
sql
SELECT e.id, t.value AS tag
FROM events e LEFT JOIN json_each(e.payload, '$.tags') t ON true
ORDER BY e.id, t.key;| id | tag |
|---|---|
| 1 | web |
| 1 | promo |
| 2 | app |
| 3 | NULL |
PostgreSQL:
sql
SELECT e.id, t.tag
FROM events e CROSS JOIN LATERAL jsonb_array_elements_text(e.payload::jsonb -> 'tags') AS t(tag)
ORDER BY e.id, t.tag;| id | tag |
|---|---|
| 1 | promo |
| 1 | web |
| 2 | app |
Counting tags is then an ordinary GROUP BY on the expanded rows. If arrays are queried this way all the time, a child table with one row per tag may be the better design.
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
SELECT e.id, t.value AS tag
FROM events e JOIN json_each(e.payload, '$.tags') t
ORDER BY e.id, t.key;
SELECT e.id, t.value AS tag
FROM events e LEFT JOIN json_each(e.payload, '$.tags') t ON true
ORDER BY e.id, t.key;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- SQLite json_each expands arrays into rows
- PostgreSQL uses jsonb_array_elements(_text)
- Inner joins drop rows without the array
- LEFT JOIN ... ON true keeps them
Common mistakes
- Losing rows that have no array
- Parsing arrays with string functions
Follow-ups
- How would you count events per tag?
- When should the array become a child table?
Tips
- Mention the LEFT JOIN case