← Back to SQL, page 14

sql-0273 · Easy fresher

How would you extract a nested value, such as the user's country, from a JSON text column in SQLite and in PostgreSQL?

In SQLite use json_extract(payload, '$.user.country') or the ->> operator (3.38+). In PostgreSQL, cast to jsonb and use payload::jsonb -> 'user' ->> 'country', or #>> '{user,country}'. The ->> forms return text; -> returns JSON.

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;
idcountrytype
1INsignup
2FRpurchase
3INpurchase

$.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;
idcountryuser_id
1IN7
2FR8
3IN7

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