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 id, json_extract(payload, '$.user.country') AS country, payload ->> '$.type' AS type
FROM events ORDER BY id;| id | country | type |
|---|---|---|
| 1 | IN | signup |
| 2 | FR | purchase |
| 3 | IN | purchase |
$.user.country is a JSON path: start at the root, go into user, then country. A missing key returns NULL rather than an error, which is why event 3, which has no tags, can still be queried.
PostgreSQL:
sql
SELECT id, payload::jsonb -> 'user' ->> 'country' AS country, payload::jsonb #>> '{user,id}' AS user_id
FROM events ORDER BY id;| id | country | user_id |
|---|---|---|
| 1 | IN | 7 |
| 2 | FR | 8 |
| 3 | IN | 7 |
Store JSON as jsonb in PostgreSQL rather than json or text, so it is parsed once, indexable and comparable. In SQLite, JSON is text; SQLite 3.45 added an internal binary form (JSONB functions) for speed.
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 id, json_extract(payload, '$.user.country') AS country, payload ->> '$.type' AS type
FROM events ORDER BY id;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_extract or ->> with a path
- PostgreSQL: -> for JSON, ->> for text, #>> for paths
- Missing keys return NULL
- Prefer jsonb columns in PostgreSQL
Common mistakes
- Using -> and comparing JSON with text
- Storing JSON as plain text in PostgreSQL
Follow-ups
- How would you index a JSON field?
- How would you filter events by country?
Tips
- Show both engines