Sub topic 3
Indexing JSON: GIN operator classes and expression indexes
This chapter assumes you know basic SQL, can create tables, and understand how jsonb stores documents. The examples use the orders table from earlier chapters. The SQL/JSON functions in the last section require PostgreSQL 17 or later.
GIN operator classes
A GIN (Generalized Inverted Index) maps each key and value inside a jsonb document to the rows that contain it. Two operator classes matter here:
jsonb_ops(the default) supports@>,?,?|, and?&.jsonb_path_opssupports only@>, but it is usually smaller and faster for containment.
CREATE INDEX orders_details_gin ON orders USING gin (details jsonb_path_ops);
EXPLAIN SELECT id FROM orders WHERE details @> '{"status": "paid"}';On a small table, the planner may still choose a sequential scan. Check EXPLAIN output on realistic data.
Expression indexes
GIN does not help with ->> comparisons. For equality on one extracted key, a B-tree expression index works better:
CREATE INDEX orders_status_idx ON orders ((details ->> 'status'));
SELECT id FROM orders WHERE details ->> 'status' = 'paid';Querying nested data with SQL/JSON path
jsonb_path_query evaluates a path expression and returns one row per match. This path keeps array items with qty greater than 1 and returns their sku values:
SELECT id,
jsonb_path_query(details, '$.items[*] ? (@.qty > 1).sku') AS sku
FROM orders;Validating document shape with CHECK constraints
CHECK constraints reject rows that break the expected document shape:
ALTER TABLE orders
ADD CONSTRAINT details_is_object CHECK (jsonb_typeof(details) = 'object'),
ADD CONSTRAINT details_has_status CHECK (details ? 'status');Adding a constraint fails if existing rows violate it.
When to use JSON columns and when to normalize
| Situation | Choose |
|---|---|
| Fields vary per row and you read the document as a whole | `jsonb` column |
| Fields need foreign keys or frequent joins | Normalized tables |
| One field is filtered or aggregated often | Normalized column or expression index |
JSON_VALUE, JSON_QUERY and JSON_TABLE in PostgreSQL 17
PostgreSQL 17 adds SQL-standard JSON functions. JSON_VALUE returns a scalar as text, JSON_QUERY returns a JSON fragment, and JSON_TABLE turns array elements into rows:
SELECT id,
JSON_VALUE(details, '$.shipping.city') AS city,
JSON_QUERY(details, '$.items') AS items
FROM orders;
SELECT o.id, jt.sku, jt.qty
FROM orders o,
JSON_TABLE(o.details, '$.items[*]'
COLUMNS (sku text PATH '$.sku', qty int PATH '$.qty')) AS jt;Exercise
Which index supports WHERE details ->> 'customer' = 'Ada', and why not a GIN index?
Show answer
A B-tree expression index: CREATE INDEX orderscustomeridx ON orders ((details ->> 'customer')); GIN indexes serve containment and key-existence operators, not ->> equality comparisons.