← Back to SQL, page 14

sql-0275 · Medium mid

Write a query that totals purchase amounts per country from JSON event payloads.

Extract the fields with json_extract (or ->>) in the SELECT, filter on the extracted type, and GROUP BY the extracted country. Cast numeric fields when the engine returns text: SQLite's json_extract returns a number for JSON numbers, while PostgreSQL's ->> returns text that needs ::numeric.

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;
countrytotal
FR30
IN12

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;
countrytotal
FR30
IN12

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