JSON indexing and query plans
Overview
An index can accelerate frequently filtered JSON paths. SQLite supports expression indexes on deterministic expressions. PostgreSQL JSONB supports GIN indexes for suitable containment and existence queries, and B-tree expression indexes for scalar equality and range predicates. Choose according to the actual query rather than indexing every field.
First example
SELECT id FROM jx_product WHERE json_extract(doc,'$.category')='office' ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1 ], [ 2 ]]How it works
The fixture indexes json_extract(doc,'$.category'). SQLite expects the indexed expression to match the query expression; equivalent syntax need not match. The first query uses that expression. The second uses EXPLAIN QUERY PLAN with INDEXED BY to verify the named index can serve the predicate; forcing an index is a teaching diagnostic, not a production recommendation. Plan wording and optimizer choices depend on version and data. A separate edge test checks the unforced plan on this fixture. PostgreSQL GIN jsonb_ops and jsonb_path_ops support different operator sets; the latter does not support key-existence operators. Indexes add storage and write costs. Benchmark realistic workloads before making performance claims.
Practical example
EXPLAIN QUERY PLAN SELECT id FROM jx_product INDEXED BY jx_category_idx WHERE json_extract(doc,'$.category')='office';Observed SQLite result (rows in JSON):
[ [ 3, 0, 0, "SEARCH jx_product USING INDEX jx_category_idx (<expr>=?)" ]]Practice and mistakes
Practice: compare the query plan using doc->>'$.category' with the indexed json_extract expression. Hint 1: run EXPLAIN QUERY PLAN without INDEXED BY. Hint 2: look for SEARCH versus SCAN, not execution time from this tiny fixture.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE TEMP TABLE jx_pg(id integer PRIMARY KEY,doc jsonb);INSERT INTO jx_pg VALUES (1,'{"tags":["blue"]}'),(2,'{"tags":["red"]}');CREATE INDEX jx_pg_gin ON jx_pg USING gin(doc);SELECT id FROM jx_pg WHERE doc @> '{"tags":["blue"]}'::jsonb ORDER BY id;ROLLBACK;Expected result, not executed: [[1]]