← Back to SQL, page 14

sql-0277 · Hard senior

How would you index JSON data so that filters on a JSON field are fast?

For a specific field, create an expression index on the extracted value, in SQLite or PostgreSQL. For containment queries over many keys in PostgreSQL, a GIN index on a jsonb column supports @> and key-existence operators. Queries must use the same expression or operator for the index to apply.

Full answer

An expression index in SQLite:

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
CREATE INDEX events_type ON events (json_extract(payload, '$.type'));
EXPLAIN QUERY PLAN SELECT id FROM events WHERE json_extract(payload, '$.type') = 'purchase';
text
QUERY PLAN
SEARCH events USING INDEX events_type (<expr>=?)

The plan searches the index because the WHERE uses the indexed expression exactly.

PostgreSQL's GIN index serves containment queries such as "events whose payload contains type purchase":

sql
ALTER TABLE events ALTER COLUMN payload TYPE jsonb USING payload::jsonb;
CREATE INDEX events_payload_gin ON events USING gin (payload);
SELECT id FROM events WHERE payload @> '{"type": "purchase"}' ORDER BY id;
id
2
3

The containment query returns events 2 and 3. On a table this small the planner prefers a sequential scan, so the result shows the operator working, not the index; on a large table the planner would use the GIN index for @> (plan not shown here). jsonb_path_ops makes a smaller, faster GIN index that supports only @>.

If a field is filtered constantly, promoting it to a real column (or a generated column) is usually simplest and gives normal statistics to the planner.

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}');

CREATE INDEX events_type ON events (json_extract(payload, '$.type'));
EXPLAIN QUERY PLAN SELECT id FROM events WHERE json_extract(payload, '$.type') = 'purchase';

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Expression indexes serve one extracted field
  • GIN on jsonb serves containment and key-existence queries
  • Queries must match the indexed expression or operator
  • Promote hot fields to real columns

Common mistakes

  • Indexing the whole JSON text with a B-tree
  • Querying with ->> when only @> is indexed

Follow-ups

  • What is jsonb_path_ops?
  • Why do planners need statistics on JSON fields?

Tips

  • Distinguish field indexes from containment indexes