Interview's MateData Engineer
Interview's Mate

Data Engineer

SQL · Spark · Lakehouse · Streaming

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Engineer topics
Lesson 28/ 160
02. Advanced SQL & Relational Databases

Working with Semi-Structured Data in SQL (JSONB, Arrays, UNNEST)

Query JSONB and arrays natively, then unnest nested structures into relational rows.

IntermediateJSONB · Arrays · UNNEST3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Schema id, version, and required paths. Next, typed path values and null-safe defaults. Finally, only high-value JSON predicates or promote columns.

Think of it like…

JSON is a flexible parcel with nested pockets; UNNEST opens a chosen pocket and places every item on its own line in a relational ledger.

Where you’ve seen it

SELECT e.id, item->>'sku' sku FROM events e CROSS JOIN LATERAL jsonb_array_elements(e.payload->'items') item WHERE e.payload @> '{"status":"paid"}'; a GIN index can support the containment predicate.

Words you’ll hear

JSONB
PostgreSQL's decomposed binary JSON type with operators, indexing, and normalized object-key ordering.
Arrays
Ordered same-type values in a native database column; element cardinality and nulls still require explicit handling.
UNNEST
A set-returning operation that turns array or collection elements into rows for relational joins and aggregation.
Operational boundary
Indexing a JSON blob does not make every expression efficient, unnesting multiple arrays in a SELECT changes pairing/cardinality, and casting dynamic fields can abort the whole load on malformed values. Promote frequently queried JSON fields into typed columns, use GIN only for measured JSON containment patterns, use jsonb_to_recordset or explicit zipped arrays, and validate or safe_cast at the ingestion boundary.

Visual diagram

Loading interactive diagram

Theory & deep dive

JSONB: the working mechanism

Native JSONB and array operations let SQL preserve flexible payload fields and then relationalize them with path operators, filtering, and UNNEST without round-tripping through application parsing.

Schema id, version, and required paths. Typed path values and null-safe defaults, then LATERAL expansion at known grain; this exposes the state governed by UNNEST.

Working with Semi-Structured Data in SQL in one concrete design

SELECT e.id, item->>'sku' sku FROM events e CROSS JOIN LATERAL jsonb_array_elements(e.payload->'items') item WHERE e.payload @> '{"status":"paid"}'; a GIN index can support the containment predicate.

Key takeaway: Native JSONB and array operations let SQL preserve flexible payload fields and then relationalize them with path operators, filtering, and UNNEST without round-tripping through application parsing

Working with Semi-Structured Data in SQL: failure mode and production response

Indexing a JSON blob does not make every expression efficient, unnesting multiple arrays in a SELECT changes pairing/cardinality, and casting dynamic fields can abort the whole load on malformed values.

Promote frequently queried JSON fields into typed columns, use GIN only for measured JSON containment patterns, use jsonb_to_recordset or explicit zipped arrays, and validate or safe_cast at the ingestion boundary. Track JSON GIN as "helps containment and key-existence patterns, not every cast", and make Path extraction visible to the dataset owner.

Key takeaway: Promote frequently queried JSON fields into typed columns, use GIN only for measured JSON containment patterns, use jsonb_to_recordset or explicit zipped arrays, and validate or safe_cast at the ingestion boundary.

How it works, step by step

Step 1 of 4
JSONB

1. Validate envelope

Schema id, version, and required paths. Native JSONB and array operations let SQL preserve flexible payload fields and then relationalize them with path operators, filtering, and UNNEST without round-tripping through application parsing.

schema id, version, and required paths
Key numbers at this step
JSON GIN
helps containment and key-existence patterns, not every cast
Arrays
Ordered same-type values in a native database column; element cardinality and nulls still require explicit handling.

When to use it & trade-offs

What it is

Native JSONB and array operations let SQL preserve flexible payload fields and then relationalize them with path operators, filtering, and UNNEST without round-tripping through application parsing. SELECT e.id, item->>'sku' sku FROM events e CROSS JOIN LATERAL jsonb_array_elements(e.payload->'items') item WHERE e.payload @> '{"status":"paid"}'; a GIN index can support the containment predicate.

Why it matters: Indexing a JSON blob does not make every expression efficient, unnesting multiple arrays in a SELECT changes pairing/cardinality, and casting dynamic fields can abort the whole load on malformed values. Promote frequently queried JSON fields into typed columns, use GIN only for measured JSON containment patterns, use jsonb_to_recordset or explicit zipped arrays, and validate or safe_cast at the ingestion boundary.

When to reach for it

  • Query JSONB and arrays natively, then unnest nested structures into relational rows.
  • Choose JSONB because it provides this capability: PostgreSQL's decomposed binary JSON type with operators, indexing, and normalized object-key ordering.
  • Keep evidence for JSON GIN at "helps containment and key-existence patterns, not every cast" so the last production stage-Index - only high-value JSON predicates or promote columns-remains testable.

When to avoid or be careful

  • Indexing a JSON blob does not make every expression efficient, unnesting multiple arrays in a SELECT changes pairing/cardinality, and casting dynamic fields can abort the whole load on malformed values.
  • Do not conflate Arrays with JSONB. The second concept contributes different behavior: Ordered same-type values in a native database column; element cardinality and nulls still require explicit handling.
  • Release only after this guardrail is in place: Promote frequently queried JSON fields into typed columns, use GIN only for measured JSON containment patterns, use jsonb_to_recordset or explicit zipped arrays, and validate or safe_cast at the ingestion boundary.

JSONB / Arrays / UNNEST - roles, limits, and operating cost

JSONB
Best for: PostgreSQL's decomposed binary JSON type with operators, indexing, and normalized object-key ordering.

Strengths: PostgreSQL's decomposed binary JSON type with operators, indexing, and normalized object-key ordering. Native JSONB and array operations let SQL preserve flexible payload fields and then relationalize them with path operators, filtering, and UNNEST without round-tripping through application parsing.

Watch out: Indexing a JSON blob does not make every expression efficient, unnesting multiple arrays in a SELECT changes pairing/cardinality, and casting dynamic fields can abort the whole load on malformed values.

Arrays
Best for: Ordered same-type values in a native database column; element cardinality and nulls still require explicit handling.

Strengths: Ordered same-type values in a native database column; element cardinality and nulls still require explicit handling. In this workflow it supports: Relationalize - LATERAL expansion at known grain.

Watch out: The operating cost is real: -> returns JSONB, ->> returns text.

UNNEST
Best for: A set-returning operation that turns array or collection elements into rows for relational joins and aggregation.

Strengths: A set-returning operation that turns array or collection elements into rows for relational joins and aggregation. Its output can be checked with Relationalized grain.

Watch out: Operating guardrail: Promote frequently queried JSON fields into typed columns, use GIN only for measured JSON containment patterns, use jsonb_to_recordset or explicit zipped arrays, and validate or safe_cast at the ingestion boundary.

Interview signals & numbers to know

When this topic comes up

  • “Where is the failure boundary for JSONB, and how would JSON GIN reveal it?”
  • “Why is Arrays distinct from this behavior: a set-returning operation that turns array or collection elements into rows for relational joins and aggregation?”
  • Production clue: Indexing a JSON blob does not make every expression efficient, unnesting multiple arrays in a SELECT changes pairing/cardinality, and casting dynamic fields can abort the whole load on malformed values.
  • Design probe: Promote frequently queried JSON fields into typed columns, use GIN only for measured JSON containment patterns, use jsonb_to_recordset or explicit zipped arrays, and validate or safe_cast at the ingestion boundary.

Benchmarks & rules of thumb

JSON GIN -
helps containment and key-existence patterns, not every cast
Path extraction -
`->` returns JSONB, `->>` returns text
Relationalized grain -
one output row per explicitly selected array element

Common mistakes & follow-ups

Common interview mistakes

  • Indexing a JSON blob does not make every expression efficient, unnesting multiple arrays in a SELECT changes pairing/cardinality, and casting dynamic fields can abort the whole load on malformed values.
  • Reporting success from a job exit code without checking JSON GIN and Path extraction.
  • Treating this example as complete without replay, rollback, or access boundaries: SELECT e.id, item->>'sku' sku FROM events e CROSS JOIN LATERAL jsonb_array_elements(e.payload->'items') item WHERE e.payload @> '{"status":"paid"}'; a GIN index can support the containment predicate.

Likely interviewer follow-ups

  • How would you prove this contract instead of only checking that the command ran: PostgreSQL's decomposed binary JSON type with operators, indexing, and normalized object-key ordering.
  • What does the recovery plan do when this occurs? Indexing a JSON blob does not make every expression efficient, unnesting multiple arrays in a SELECT changes pairing/cardinality, and casting dynamic fields can abort the whole load on malformed values.
  • When is JSONB insufficient for Path extraction, and what does adding Arrays cost in JSON GIN?
Interview tip: Lead with the data path and failure boundary: Native JSONB and array operations let SQL preserve flexible payload fields and then relationalize them with path operators, filtering, and UNNEST without round-tripping through application parsing. Then make the answer operational: Promote frequently queried JSON fields into typed columns, use GIN only for measured JSON containment patterns, use jsonb_to_recordset or explicit zipped arrays, and validate or safe_cast at the ingestion boundary.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Working with Semi-Structured Data in SQL (JSONB, Arrays, UNNEST) with data engineer interview Q&A and hands-on practice.

Open Data Engineer Q&A →Machine Learning Q&A
Previous topic
Aggregations, GROUPING SETS, ROLLUP & CUBE
Next topic
Regex, String Manipulation & Date/Time Interval Operations in SQL