JSON Processing in SQL
Master JSON in SQL
JSON is the lingua franca of APIs and semi-structured data. SQL databases provide powerful operators to extract, transform, aggregate, and index JSON — turning unstructured blobs into queryable, analyzable data.
- PostgreSQL —
->,->>,@?, GIN indexes for jsonb - BigQuery —
JSON_EXTRACT_SCALAR,JSON_EXTRACT_ARRAY - SQL Server —
JSON_VALUE,JSON_QUERY,OPENJSON - MySQL —
JSON_EXTRACT,->>,JSON_TABLE
In interviews, JSON questions test your ability to navigate nested structures, unnest arrays, and build aggregations from semi-structured sources.
What Is JSON in SQL?
SQL databases store JSON as text with special operators for extraction, transformation, and indexing. The two main types are:
PostgreSQL: json vs jsonb
| Feature | json | jsonb |
|---|---|---|
| Storage | Raw text | Decomposed binary |
| Indexing | GIN index (slow) | GIN index (fast) |
| Operators | All | All + @?, @@ |
| Performance | Slower | 2-5x faster |
| Duplicate keys | Preserved | Removed (last wins) |
Always use jsonb in PostgreSQL — it's faster for extraction and supports GIN indexing.
jsonb does more than store the same text faster; it canonicalises it. Key order becomes the binary ordering, duplicate keys collapse to the last occurrence, and insignificant whitespace disappears, so two documents that differ only in formatting compare equal after the cast. The cost lands on write: parsing, normalising and rebuilding the binary value on every INSERT or UPDATE of the column, plus a physically larger row when the document carries many small keys. A workload that only appends raw payloads and never queries them is the one case where the plain json type remains the cheaper column.
JSON Extraction Operators
PostgreSQL Operators
-- Basic JSON extraction
SELECT
id,
data->>'name' AS name, -- Text extraction
data->'address'->>'city' AS city, -- Nested extraction
data->'preferences'->'notifications'->>'email' AS email_pref,
(data->>'age')::INT AS age, -- Type casting
jsonb_array_length(data->'tags') AS tag_count
FROM users;
BigQuery Functions
-- BigQuery JSON extraction
SELECT
id,
JSON_EXTRACT_SCALAR(data, '$.name') AS name,
JSON_EXTRACT_SCALAR(data, '$.address.city') AS city,
JSON_EXTRACT(data, '$.tags') AS tags_json,
JSON_EXTRACT_ARRAY(data, '$.orders') AS orders_array,
ARRAY(
SELECT JSON_EXTRACT_SCALAR(item, '$.name')
FROM UNNEST(JSON_EXTRACT_ARRAY(data, '$.tags')) AS item
) AS tag_names
FROM `project.dataset.users`;
The operator you pick decides what the next operator can do. -> returns JSON, so it chains into another -> and feeds jsonb_array_length; ->> returns text, so it is what you compare, cast or concatenate, and (data->>'age')::INT is required before any numeric comparison — data->'age' against the integer 30 does not compile at all, because PostgreSQL has no implicit cast from an integer to jsonb. A missing key returns NULL instead of raising, and SQL NULL propagates through a chain, so data->'address'->>'city' yields NULL when any link is missing. That is usually what you want in a projection, and it is occasionally how a malformed document hides behind an apparently working query.
JSON Path Expressions
-- Advanced JSON path queries (PostgreSQL 12+)
SELECT
id,
data @? '$.orders[*]?(@.amount > 1000)' AS has_large_orders,
jsonb_path_query_array(data, '$.tags[*]') AS all_tags,
jsonb_path_query_first(data, '$.orders[0].items[0].name') AS first_item,
jsonb_path_query(data, '$.orders[*]?(@.status == "pending")') AS pending_orders
FROM users;
Path queries are the set-based alternative to walking a document by hand. @? answers an existence question and is the form a GIN index can serve, jsonb_path_query_array collects every match into a single array so the document is parsed once per row, and jsonb_path_query returns one row per match when the matches themselves need aggregating. The filter syntax inside the path is evaluated by the jsonb path engine rather than by SQL, which means 1000 there is a JSON number; quoting it as a string silently matches nothing and returns an empty array with no error to explain why.
JSON Aggregation
-- Aggregate rows INTO JSON array
SELECT
department_id,
jsonb_agg(
jsonb_build_object(
'employee_id', employee_id,
'name', name,
'salary', salary
)
) AS employees,
jsonb_agg(name ORDER BY salary DESC) AS names_by_salary
FROM employees
GROUP BY department_id;
-- Aggregate rows INTO JSON object (key-value map)
SELECT
jsonb_object_agg(
employee_id::TEXT,
jsonb_build_object('name', name, 'salary', salary)
) AS employee_map
FROM employees
WHERE department_id = 1;
jsonb_agg accepts an ORDER BY and dropping it is the usual source of a flaky JSON API: group ordering carries no guarantee, so the array order can change between runs, between replica nodes, and after an unrelated change to the plan. The aggregate also skips NULLs the way every other aggregate does, so a NULL salary is absent from the array rather than present as JSON null — if the payload must distinguish those two cases, feed a COALESCE'd value in. jsonb_object_agg has its own failure mode: it raises a duplicate-key error when the expression chosen for the key repeats, which is exactly why the examples key on employee_id rather than on name.
JSON Transformation
-- Transform JSON structure
SELECT
id,
jsonb_build_object(
'full_name', data->>'first_name' || ' ' || data->>'last_name',
'contact', jsonb_build_object(
'email', data->>'email',
'phone', data->'phone_numbers'->0
),
'order_count', jsonb_array_length(data->'orders'),
'total_spent', (
SELECT SUM((item->>'amount')::NUMERIC)
FROM jsonb_array_elements(data->'orders') AS item
)
) AS transformed_data
FROM users;
JSON Array Processing
-- Unnest JSON array into rows
SELECT
u.id,
u.data->>'name' AS user_name,
tag.value AS tag
FROM users u,
LATERAL jsonb_array_elements_text(u.data->'tags') AS tag(value);
-- Filter JSON array elements
SELECT
u.id,
jsonb_path_query_array(
u.data->'orders',
'$[*]?(@.amount > 100)'
) AS large_orders
FROM users u;
-- Aggregate JSON array values
SELECT
u.id,
(SELECT SUM((item->>'amount')::NUMERIC)
FROM jsonb_array_elements(u.data->'orders') AS item
WHERE item->>'status' = 'completed') AS total_completed
FROM users u;
Unnesting changes the grain of the query: one row per user becomes one row per tag, and every measure computed after that point is per tag unless a GROUP BY puts it back. LATERAL jsonb_array_elements_text in the FROM clause does the multiplication where you can see it while the outer projection stays intact; calling the same set-returning function in a SELECT list multiplies rows there instead, and the difference stays invisible until a SUM comes out twice as large as the source. The correlated-subquery form over jsonb_array_elements avoids the issue entirely by aggregating inside the subquery and handing exactly one value back to the outer row.
JSON Merge and Patch
-- Merge two JSON objects (right overrides left)
SELECT jsonb_merge_patch(
'{"name": "John", "age": 30}'::jsonb,
'{"age": 31, "city": "NYC"}'::jsonb
);
-- Result: {"name": "John", "age": 31, "city": "NYC"}
-- Patch with null removal (null deletes key)
SELECT jsonb_merge_patch(
'{"a": 1, "b": 2, "c": 3}'::jsonb,
'{"b": null, "d": 4}'::jsonb
);
-- Result: {"a": 1, "c": 3, "d": 4}
JSON in UPDATE Statements
-- Update specific JSON path
UPDATE users
SET data = jsonb_set(data, '{address, city}', '"San Francisco"')
WHERE id = 101;
-- Add new key to JSON object
UPDATE users
SET data = data || '{"newsletter_subscribed": true}'::jsonb
WHERE data->>'status' = 'active';
-- Remove key from JSON object
UPDATE users
SET data = data - 'temp_field'
WHERE data ? 'temp_field';
JSON Indexing
-- GIN index for general JSON queries (fastest for containment)
CREATE INDEX idx_users_data ON users USING GIN (data);
-- Specific path index (B-tree on extracted value)
CREATE INDEX idx_users_email ON users ((data->>'email'));
-- Partial index for specific values
CREATE INDEX idx_active_users ON users ((data->>'status'))
WHERE data->>'status' = 'active';
Which index fits depends on the operator rather than on the column type. A GIN index over the whole document serves containment and existence tests — @>, ?, @? — because it is an inverted index over every key and value inside the document, and it is useless for WHERE data->>'email' = 'x', which is an equality on a derived scalar and needs a B-tree over the expression instead. The pair covers nearly every workload: GIN for shape questions, expression B-tree for scalar lookups, and a partial B-tree when the lookup only ever targets one status. On a million rows a default GIN index over a modest document runs to tens of megabytes and adds visible cost to every insert, which is why jsonb_path_ops — the smaller operator class that supports containment only — is the better default whenever @> is the only predicate in play.
⚠️
Performance Tip: Use jsonb instead of json in PostgreSQL. jsonb is stored in a decomposed binary format that supports GIN indexing and is significantly faster for queries. The json type requires re-parsing on every extraction.
Quiz: Test Your Knowledge
Follow-Up Questions
- What's the difference between
jsonandjsonbin PostgreSQL? - How would you index a JSON column for efficient range queries?
- Explain the performance implications of using JSON vs normalized tables.
- How do you handle schema evolution in JSON documents?
- What's the best approach for querying deeply nested JSON structures?
Common Mistakes
Comparing a jsonb value against an integer directly and hitting an operator-does-not-exist error
Fix: Extract with ->>, cast to the SQL type, then compare — (data->>'age')::INT >= 30 — because no implicit cast exists between integers and jsonb
Calling jsonb_agg without ORDER BY and discovering the array order changes between runs and nodes
Fix: Put ORDER BY inside the aggregate; group ordering carries no guarantee once the plan or the replica changes
Expecting a GIN index to serve an equality filter on an extracted field such as data->>'email'
Fix: GIN answers containment and existence operators; scalar equality needs a B-tree over the extracted expression, so keep one of each
Key Takeaways
- Use
jsonboverjson— binary storage + GIN indexing = 2-5x faster ->returns JSON,->>returns text — use->>for comparison/casting- GIN index on jsonb for
@?,@@,?operators; B-tree for->>equality - jsonb_array_elements_text unnests text arrays; jsonb_array_elements unnests objects
- jsonb_merge_patch for combining/patching JSON documents
- BigQuery: Use
JSON_EXTRACT_SCALARfor text,JSON_EXTRACTfor JSON