🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

JSON in SQL: JSON_TABLE, Path Queries, and JSONB Indexing

Advanced SQLJSON Operations⭐ Premium

Two ways to be wrong with JSON columns

Storing JSON in a relational column is a trade, and teams usually discover they have signed the wrong half of it six months later. The two failure modes are symmetrical. Put JSON in a column and treat it as opaque, and every question becomes a scan plus a parse, with no constraint to stop a typo from becoming the canonical record of a payment. Normalise everything on arrival, and you pay an ETL cycle for a field nobody has queried yet.

The working middle is deliberate: keep payloads that are genuinely semi-structured and loosely evolving as JSON, project the fields you query into real columns or expressions, and index those projections. The column holds the truth as it arrived; the projections and indexes hold the parts you have decided matter. Once you can articulate which fields are contractual and which are incidental, the modelling decision almost makes itself.

By the end of this lesson you should be able to write path extraction and shredding queries that the optimiser can push down, choose an index that supports your predicate instead of a full document scan, and decide when a JSON field should be promoted to a column.

Extraction paths and shredding, side by side

Engines differ in surface syntax but agree on the shape of the operation: address a value by path, coerce it to a type, and either return it as a scalar or flatten it into rows. The choice between scalar extraction and shredding depends entirely on whether you want one value per row or many rows per row.

OperationPostgreSQLMySQLOracle / SQL:2016
Extract as JSONcol -> 'a'JSON_EXTRACTJSON_VALUE with return type
Extract as textcol ->> 'a'JSON_UNQUOTEJSON_VALUE returning VARCHAR
Nested pathcol #>> '{a,b,0}'path syntax with $JSON_VALUE(col, '$.a.b[0]')
Existence testcol ? 'a'JSON_CONTAINS_PATHJSON_EXISTS
Shred to rowsjsonb_to_recordsettable functionsJSON_TABLE
Type checkjsonb_typeofJSON_TYPEtype-aware functions
Validate on insertjsonb_typeof checkJSON_SCHEMA_VALIDIS JSON constraint

Two pitfalls sit inside that table. Coercing with the text operator and then comparing to a number makes the database compare strings, so "10" sorts after "9" and a filter silently keeps the wrong rows. And paths are case-sensitive and position-sensitive in the source document: a producer that renames a key or reorders an array breaks nothing at insert time and breaks every reader at query time.

Shredding documents into relational rows

JSON_TABLE is the standard answer to "I need this array as rows". It projects the document into a virtual table with declared columns and cardinality, which means the rest of the query is ordinary SQL that the optimiser can plan, join, and prune.

SELECT o.order_id,
       jt.line_no,
       jt.sku,
       jt.qty,
       jt.unit_price
  FROM orders o
  CROSS JOIN JSON_TABLE(
       o.payload,
       '$.lines[*]' COLUMNS (
           line_no    FOR ORDINALITY,
           sku        VARCHAR(40)  PATH '$.sku',
           qty        INTEGER      PATH '$.qty',
           unit_price DECIMAL(12,2) PATH '$.price'
       )
  ) AS jt
 WHERE o.order_date >= DATE '2026-01-01'
   AND jt.qty  IS NOT NULL
   AND jt.qty  > 0;

Three details make this production-grade rather than illustrative. FOR ORDINALITY preserves array position so the result is deterministic and joinable back to a line number. Declared types mean bad values surface as errors you can trap rather than as strings compared in ways nobody intended. And pushing a WHERE clause on the shredded columns lets the engine filter during shredding instead of materialising every line first.

PostgreSQL reaches the same place with set-returning functions, which are useful to know when a document holds a map rather than a list.

-- Turn a JSON object of counters into rows you can aggregate
SELECT o.order_id,
       metrics.key   AS metric,
       metrics.value AS value
  FROM orders o,
       LATERAL jsonb_each(o.counters) AS metrics(key, value)
 WHERE o.order_date >= CURRENT_DATE - INTERVAL '7 days';

-- Typed projection where the document shape is stable
SELECT order_id, customer.tier, customer.region
  FROM orders,
       jsonb_to_record(payload)
         AS customer(tier varchar(20), region varchar(20));

LATERAL is what makes the row-per-entry pattern work: the function is evaluated once per outer row with access to that row's document, exactly like a correlated subquery but returning a set.

Indexing JSONB without regret

An index on a JSON column is useless on its own; the optimiser has to parse every document to use it. Index the extracted expression instead, and suddenly predicates that looked like full scans become range scans over a btree.

-- Expression index on a frequently filtered field
CREATE INDEX idx_orders_customer_id
    ON orders ((payload ->> 'customer_id'));

-- GIN index supporting containment and key-existence predicates
CREATE INDEX idx_orders_payload
    ON orders USING GIN (payload jsonb_path_ops);

-- Partial index: only the rows anyone actually queries
CREATE INDEX idx_orders_open
    ON orders ((payload ->> 'status'))
 WHERE (payload ->> 'status') IN ('open', 'pending');

-- Query planner now uses the expression index
SELECT order_id, payload ->> 'status' AS status
  FROM orders
 WHERE payload ->> 'customer_id' = 'C-4821'
   AND payload ->> 'status' = 'open';

The three index types answer three different questions. An expression btree serves equality and range on a single extracted field. A GIN index with jsonb_path_ops serves containment — "does the document contain this key and value" — very efficiently but does not help inequality or ordering. A partial index serves the small hot subset, which is usually the status filter that every query includes and that matches only a few percent of rows.

The trap is indexing every field that appears in a WHERE clause once. Each expression index costs storage and slows every insert and update on that table. Promote fields in order of query frequency and selectivity, and measure with EXPLAIN (ANALYZE, BUFFERS) before and after rather than guessing.

Mutating documents safely

Updates that rewrite JSON have two hazards: they replace the whole document when you meant to change a value, and they destroy concurrent edits made between read and write. Prefer operators that target a path, and think about concurrency the same way you would for any read-modify-write.

-- Targeted update: leaves every other key untouched
UPDATE orders
   SET payload = jsonb_set(payload, '{tags,urgent}', '"high"', true),
       updated_at = now()
 WHERE order_id = 4821;

-- Append to an array without rewriting the whole document by hand
UPDATE orders
   SET payload = payload || '{"notes":[{"at":"2026-02-11","text":"called"}]}'::jsonb
 WHERE order_id = 4821;

-- Atomic increment guarded by a row lock
UPDATE orders
   SET payload = jsonb_set(
           payload,
           '{retry_count}',
           to_jsonb(COALESCE((payload ->> 'retry_count')::integer, 0) + 1)
       )
 WHERE order_id = 4821;

jsonb_set with create_missing controls whether a missing path is created or left alone — turning that flag off is how you avoid manufacturing empty objects on rows that simply lack the field. For concurrent counters, remember that JSONB offers no read-modify-write guarantee of its own: either do the arithmetic inside the UPDATE under the row lock, as above, or move the counter into a real column where the engine's atomic semantics apply.

Schema evolution for semi-structured columns

JSON's flexibility means evolution happens by default rather than by decision, so impose one. Additive changes — new optional keys — are safe if readers ignore unknown fields, which they should. Renames and type changes are breaking even though nothing fails at insert time, and the only defence is validating on write.

ALTER TABLE orders
    ADD CONSTRAINT chk_orders_payload_shape
    CHECK (jsonb_typeof(payload) = 'object'
           AND payload ? 'order_id'
           AND payload ? 'lines'
           AND jsonb_typeof(payload -> 'lines') = 'array');

-- Promote a field that has become contractual
ALTER TABLE orders
    ADD COLUMN customer_id bigint
    GENERATED ALWAYS AS ((payload ->> 'customer_id')::bigint) STORED;

CREATE INDEX idx_orders_customer_id_col ON orders (customer_id);

A generated column is the bridge between the two worlds: the payload stays authoritative while the projected field participates in constraints, indexes, joins, and statistics. When a field graduates from incidental to contractual, promote it — and keep validating the payload so the projection can never disagree with its source.

âš ī¸Text comparison is not numeric comparison

Extracting with a text operator and comparing to a number invites lexicographic surprises, and casting inside the predicate can defeat the expression index. Extract with the typed operator, or cast once in a generated column, so the comparison and the index use the same type.

Common Mistakes

Filtering on a JSON field with no supporting index and accepting a sequential scan

Fix: Create an expression index on the extracted value, or promote the field to a generated column

Comparing extracted text against numbers, producing lexicographic results

Fix: Extract with typed operators or cast in a generated column so both sides share a type

Rewriting an entire document for a one-key change, clobbering concurrent edits

Fix: Use jsonb_set or the concat operator so only the addressed path changes

Letting producers rename keys with no validation

Fix: Add a shape check constraint and version the payload when a breaking change is unavoidable

Best Practices

  • Project frequently filtered JSON fields into typed generated columns and index those
  • Prefer GIN containment for existence queries and btree expressions for range queries
  • Validate shape on insert so bad documents fail loudly at the boundary
  • Use JSON_TABLE or lateral functions to shred documents into rows before joining
  • Review index counts on JSON tables regularly; each one taxes every write

Interview Questions

Q1: Difference between a JSON and JSONB column in PostgreSQL?

JSON preserves exact text and duplicate keys; JSONB parses to a binary form that supports indexing and containment but drops formatting and duplicate keys.

Q2: How do you index a JSON field for equality queries?

Create an expression index on the extracted value, or promote the field to a generated column and index that.

Q3: When would you use JSON_TABLE?

When you need array elements as rows with declared types, so the rest of the query can be planned as ordinary relational SQL.

Q4: What is the risk of updating JSON in place?

Read-modify-write races and whole-document replacement; target the path and do numeric changes under the row lock.

Key Takeaways

  • Treat the JSON column as the source of truth and projections as queryable mirrors
  • Shred with JSON_TABLE or lateral functions so the optimiser sees real columns
  • Index expressions or generated columns, never the raw document
  • Validate shape on write because JSON evolves silently otherwise
  • Promote a field to a column the moment it carries a constraint or a join
🔒

Premium Content

JSON in SQL: JSON_TABLE, Path Queries, and JSONB Indexing

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement