← Back to SQL, page 14

sql-0274 · Medium mid

How do you turn a JSON array inside a row into one row per element?

In SQLite join the table to json_each(payload, '$.tags'), which returns one row per array element with a value column. In PostgreSQL use jsonb_array_elements_text(payload::jsonb -> 'tags') in a lateral join. Rows without the array produce no output with an inner join; use LEFT JOIN to keep them.

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;
idtag
1web
1promo
2app

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;
idtag
1web
1promo
2app
3NULL

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;
idtag
1promo
1web
2app

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