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 json_extract(payload, '$.user.country') AS country, SUM(json_extract(payload, '$.amount')) AS total
FROM events
WHERE json_extract(payload, '$.type') = 'purchase'
GROUP BY country ORDER BY country;| country | total |
|---|---|
| FR | 30 |
| IN | 12 |
India has one purchase of 12 and France one of 30. The signup event has no amount and is excluded by the type filter.
PostgreSQL needs a cast, because ->> returns text:
sql
SELECT payload::jsonb -> 'user' ->> 'country' AS country, SUM((payload::jsonb ->> 'amount')::numeric) AS total
FROM events WHERE payload::jsonb ->> 'type' = 'purchase'
GROUP BY 1 ORDER BY 1;| country | total |
|---|---|
| FR | 30 |
| IN | 12 |
If this report runs often, extract the fields into real columns, or use a generated column or an expression index, such as CREATE INDEX ON events ((payload ->> '$.type')) in SQLite, so the filter does not parse every payload.
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 json_extract(payload, '$.user.country') AS country, SUM(json_extract(payload, '$.amount')) AS total
FROM events
WHERE json_extract(payload, '$.type') = 'purchase'
GROUP BY country ORDER BY country;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- Extract fields in SELECT, WHERE and GROUP BY
- SQLite json_extract keeps JSON numbers numeric
- PostgreSQL ->> returns text; cast to numeric
- Index extracted expressions for frequent queries
Common mistakes
- Summing text values in PostgreSQL
- Parsing every payload on every report query
Follow-ups
- How would you make this fast on millions of rows?
- What happens with a malformed payload?
Tips
- Mention the cast difference