JSON in SQL: Extraction, Indexing, Shredding
Modern schemas carry flexible payloads â feature flags, webhook bodies, API responses. Databases let you keep them queryable without a separate document store, if you know where the line is.
- json versus jsonb â text fidelity versus parsed binary speed and indexing
- Extraction toolkit â operators, path syntax, and containment queries
- Indexes that actually fire â GIN, expression, and generated-column strategies
- Shredding responsibly â promoting hot fields to real columns without losing the document JSON columns are a tool, not a modeling philosophy.
Prerequisites
- !Comfort with SELECT and basic filtering
- !Familiarity with the idea that databases store typed values
- !Access to PostgreSQL 14+ or MySQL 8+ to run the examples
What You'll Learn
- 1Choose between storing JSON as text, native JSON, or shredded columns
- 2Extract values with engine-appropriate operators and path expressions
- 3Index the JSON paths your queries filter on
- 4Promote fields from JSON to relational columns as usage stabilizes
When a JSON Column Is the Right Call
JSON columns earn their place when the payload shape varies per row, arrives from an external system you do not control, or is read mostly as a whole. Feature-flag documents, nested configuration blobs, audit metadata, and third-party webhook payloads are typical fits. The moment you routinely filter or aggregate on an inner field across millions of rows, that field wants to be a real column â typed, constrained, indexable without gymnastics, and visible to everyone reading the schema.
Three storage strategies sit on a spectrum:
| Strategy | Strengths | Costs | Use when |
|---|---|---|---|
| TEXT column with manual parsing | Maximum portability | No validation, no indexes, parsing in app code | Tiny payloads or extreme portability needs |
| Native JSON type | Validation, path operators, specialized indexes | Engine-specific syntax, larger storage | Flexible attributes queried occasionally |
| Shredded relational columns | Constraints, joins, simple indexes, clarity | Schema migration effort | Fields used in WHERE, JOIN, GROUP BY, or reports |
PostgreSQL distinguishes json (stores the exact text, re-parsed on every use) from jsonb (stores a decomposed binary form, normalized and faster to query). In practice you almost always want jsonb. MySQL 8 provides a single JSON type that validates on insert, stores a binary representation internally, and exposes a rich function library.
-- PostgreSQL: create a flexible attributes column, then extract from it
CREATE TABLE products (
product_id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL,
price NUMERIC(10, 2) NOT NULL,
attributes JSONB NOT NULL DEFAULT '{}'::jsonb
);
INSERT INTO products (name, price, attributes) VALUES
('Trail Bottle', 24.99,
'{"color": "slate", "capacity_ml": 750, "tags": ["insulated", "bpa-free"], "specs": {"weight_g": 320}}'),
('Camp Stove', 89.50,
'{"color": "orange", "fuel": "propane", "tags": ["portable"], "specs": {"weight_g": 1450}}');
-- Arrow operators: -> returns jsonb, ->> returns text
SELECT
name,
attributes ->> 'color' AS color,
(attributes ->> 'price')::numeric AS ignored_example,
attributes -> 'specs' ->> 'weight_g' AS weight_g,
attributes -> 'tags' AS tags_jsonb
FROM products
WHERE attributes ->> 'color' = 'orange';
The -> versus ->> distinction is worth memorizing: -> keeps the value inside the JSON type so you can chain further extraction; ->> returns plain text so string functions and casts apply. Casting ->> output with ::numeric or ::date is common â but remember the predicate is then applied to the cast result, which usually cannot use a plain expression index unless you indexed the same expression.
The Extraction Toolkit
Each engine ships a family of path and search functions. PostgreSQL centers on operators and jsonb_path_query; MySQL centers on JSON_EXTRACT, JSON_UNQUOTE, and JSON_TABLE.
| Task | PostgreSQL (jsonb) | MySQL 8 |
|---|---|---|
| Get field as JSON | doc -> 'a' -> 'b' | JSON_EXTRACT(doc, '$.a.b') |
| Get field as text | doc ->> 'a' | JSON_UNQUOTE(JSON_EXTRACT(doc, '$.a')) or shorthand doc ->> '$.a' |
| Deep path | doc #>> '{a,0,b}' | JSON_EXTRACT(doc, '$.a[0].b') |
| Containment / existence | doc @> '{"status": "active"}', doc ? 'status' | JSON_CONTAINS_PATH(doc, 'one', '$.status') |
| Set a field | jsonb_set(doc, '{a}', '"x"') | JSON_SET(doc, '$.a', 'x') |
| Expand array to rows | jsonb_array_elements(doc -> 'tags') | JSON_TABLE(doc, '$.tags[*]' COLUMNS (tag VARCHAR(50) PATH '$')) |
| JSON-path predicate | jsonb_path_exists(doc, '$.specs ? (@.weight_g < 500)') | JSON_SEARCH / JSON_TABLE + join |
PostgreSQL's @> containment operator is special because it can use a GIN index directly â it is the fastest way to ask "does this document contain this fragment?" MySQL offers the same idea through multi-valued indexes on paths extracted with JSON_TABLE, covered later in this lesson.
-- MySQL 8: extract, shred an array into rows, and filter on a nested field
SELECT
p.product_id,
p.name,
jt.tag
FROM products p
CROSS JOIN JSON_TABLE(
p.attributes,
'$.tags[*]' COLUMNS (tag VARCHAR(50) PATH '$')
) AS jt
WHERE JSON_UNQUOTE(JSON_EXTRACT(p.attributes, '$.color')) = 'slate';
-- PostgreSQL equivalent: expand the tags array
-- SELECT p.product_id, p.name, tag
-- FROM products p
-- CROSS JOIN LATERAL jsonb_array_elements_text(p.attributes -> 'tags') AS tag
-- WHERE p.attributes ->> 'color' = 'slate';
Shredding arrays with JSON_TABLE (MySQL) or LATERAL jsonb_array_elements (PostgreSQL) turns a document into rows you can join, group, and index like any other relation â a clean middle path between raw JSON and a full schema redesign.
Making JSON Queries Actually Fast
Untreated JSON predicates are slow: each row's document must be parsed and evaluated. Indexing strategies differ by engine and by predicate shape.
PostgreSQL GIN index on the whole column. A GIN index over attributes jsonb accelerates containment (@>) and existence (?) queries â exactly the "does it have this key/value fragment" pattern. It does not accelerate ->> comparisons against arbitrary text unless you also create expression indexes.
-- PostgreSQL: GIN index accelerates containment queries
CREATE INDEX idx_products_attrs ON products USING GIN (attributes);
-- This predicate can use the GIN index:
SELECT name FROM products WHERE attributes @> '{"color": "orange"}';
-- These need expression indexes instead:
CREATE INDEX idx_products_color ON products ((attributes ->> 'color'));
CREATE INDEX idx_products_weight ON products (((attributes -> 'specs' ->> 'weight_g')::int));
SELECT name FROM products WHERE (attributes ->> 'color') = 'slate';
SELECT name FROM products WHERE ((attributes -> 'specs' ->> 'weight_g')::int) < 500;
Generated columns plus ordinary indexes. A cleaner long-term pattern: promote the hot path into a generated (stored) column and index that column like any other. PostgreSQL 12+ supports GENERATED ALWAYS AS (...) STORED; MySQL 8 supports the same idea. The JSON remains the source of truth, but the query planner sees a normal typed column.
MySQL multi-valued indexes. For arrays, MySQL can index extracted values: CREATE INDEX idx ON products ((CAST(attributes->'$.tags[*]' AS CHAR(100)) ARRAY)), letting MEMBER OF and JSON_CONTAINS probes use the index.
Whichever route you take, measure with EXPLAIN ANALYZE. JSON work is one of the areas where a plan that looks fine on ten test rows collapses on ten million.
Shredding: Promoting Fields Without Losing the Document
The mature end state for most JSON columns is hybrid: stable, widely queried fields become real columns; genuinely open-ended attributes stay in JSON. Migration does not require a big-bang rewrite.
-- Promote a hot JSON field to a typed column, backfill, then index
ALTER TABLE products ADD COLUMN color TEXT
GENERATED ALWAYS AS (attributes ->> 'color') STORED;
CREATE INDEX idx_products_color_lookup ON products (color);
-- For a permanent promotion (adds NOT NULL, constraints, and audit clarity):
-- ALTER TABLE products ADD COLUMN color_final TEXT;
-- UPDATE products SET color_final = attributes ->> 'color';
-- ALTER TABLE products ALTER COLUMN color_final SET NOT NULL;
Generated columns keep the document authoritative while giving the planner something familiar. When a field graduates to business-critical status â used in billing, compliance filters, or foreign keys â physically promote it, constrain it, and leave the JSON copy only if you still need the raw payload for replay or support tickets.
Guardrails worth adopting: validate structure on insert where the engine allows it (check constraints on jsonb with @> fragments, application-side schema validation, or MySQL's JSON type checking), cap document size to prevent unbounded growth, and never store secrets in JSON attributes that skip column-level encryption.
Validating Document Structure at the Boundary
A JSON column is a contract with every writer, and contracts need enforcement. PostgreSQL check constraints can assert required structure declaratively: a constraint using @> verifies that every row contains a fragment such as {"schema_version": 2}, and a constraint on jsonb_typeof(attributes -> 'specs') = 'object' prevents a string from appearing where an object is expected. MySQL's JSON type rejects syntactically invalid documents automatically but does not enforce shape, so structural checks there live in application code or generated-column expressions with CHECK constraints.
Practical validation policy for a team: assign a schema_version integer inside every document; validate the current and previous versions on write so rollouts can overlap; quarantine rows that fail validation into an error table with the raw payload and load timestamp, rather than rejecting the whole batch; and alert when the quarantine rate crosses a threshold. Quarantine beats rejection because one malformed upstream record should not stop a nightly load â but silence is not acceptable either, so the quarantine table needs a dashboard and an owner.
-- Structural guardrails on a JSONB attributes column (PostgreSQL)
ALTER TABLE products
ADD CONSTRAINT attrs_have_version
CHECK (attributes ? 'schema_version'),
ADD CONSTRAINT attrs_version_current
CHECK ((attributes ->> 'schema_version')::int BETWEEN 1 AND 2),
ADD CONSTRAINT attrs_specs_object
CHECK (jsonb_typeof(attributes -> 'specs') IN ('object', 'null'));
Validation belongs at the boundary closest to the writer â the application or the ingest load â not scattered through downstream consumers. When consumers must defend themselves, a view that exposes only validated fields gives them a narrow, stable surface while the raw column keeps the full payload for replay.
When to Normalize Fully Instead
JSON columns are a convenient compromise, and some workloads reveal them as the wrong compromise quickly. Reach for full normalization when any of these appear: the inner fields need foreign keys; the same entity's documents repeat shared reference data that should be conformed once; volume estimates put tens of millions of rows behind frequent JSON path filters; or compliance requires column-level encryption, masking, or row-level policies on specific attributes â all of which are simpler on real columns.
The migration path is gradual and low-risk. Add generated columns for hot paths (already shown above), backfill and index them, then flip queries to the new columns while the JSON remains authoritative. Once query logs show that a field is used everywhere â joins, constraints, reports â promote it physically: add the column with proper type and constraints, backfill with a maintenance window or an online tool, add the NOT NULL, and stop writing the field into JSON for new rows. Keep the JSON copy only if support tooling or audit replay still needs the original payload.
Teams that skip this step often rediscover it later as a data-model crisis: a JSON blob that encodes a relational schema, with no keys and no constraints, updated by six services that each parse it slightly differently. Treat JSON as a staging area for attributes whose shape has not yet earned columns â not as a permanent replacement for a schema you were too busy to design.
Common Mistakes
Filtering with ->> comparisons on millions of rows and adding no index strategy
Fix: Create expression indexes or generated columns for every frequently filtered path
Storing json (text form) in PostgreSQL when you query it at all
Fix: Use jsonb: parsed once at write, faster operators, and GIN index support
Assuming GIN indexes speed up every JSON operator
Fix: GIN accelerates containment and existence; ->> equality needs expression or generated-column indexes
Leaving billing or compliance attributes trapped in JSON
Fix: Promote them to typed, constrained columns with NOT NULL and foreign keys
Best Practices
- Default to jsonb on PostgreSQL and the JSON type on MySQL 8 rather than plain text
- Index exactly the paths your WHERE clauses touch, and verify with EXPLAIN ANALYZE
- Use generated columns to expose hot paths as typed, indexable fields
- Validate incoming documents against a schema at the application boundary
- Plan a promotion path for fields that grow in importance â JSON is a staging area, not a final home
Interview Questions
Q1: What is the difference between json and jsonb in PostgreSQL?
json stores the exact input text and re-parses on every operation. jsonb stores a normalized binary decomposition: duplicates removed, keys ordered, numbers de-normalized â faster to query and indexable with GIN, at the cost of losing original formatting and duplicate keys.
Q2: Why might a ->> equality predicate still scan the table after adding a GIN index?
GIN on the column accelerates @> containment and ? existence checks, not arbitrary ->> text comparisons. Add an expression index on (attributes ->> 'path') or a stored generated column for that path.
Q3: When should you move a field out of a JSON document entirely?
When it is used in joins, constraints, billing logic, or heavily filtered aggregates. A typed column gives validation, simpler queries, better plans, and clearer ownership of the data model.
Key Takeaways
- Native JSON types buy validation and indexing; text columns buy none of that
- Extraction operators differ per engine but the design pattern is identical: path in, typed value out
- Index the paths you filter on â GIN for containment, expression or generated columns for equality
- JSON_TABLE and lateral expansion shred arrays into rows you can join and aggregate
- Promote hot fields to real columns as they stabilize; keep JSON for genuinely open shapes