Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

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
SQL topics
Lesson 113/ 160
06. Database Design, Normalization & Semi-Structured SQL

Working with JSON & JSONB Data Types

Store semi-structured documents with JSON/JSONB and know the trade-offs.

IntermediateJSON vs JSONB · Document Storage3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

JSON columns let one column hold a whole bundle of fields. jsonb is the fast, searchable version.

Think of it like…

json is a photocopy of a form, exactly as it was filled in. jsonb is the form's answers typed into a filing system: faster to search, but it doesn't remember the handwriting or which box was filled in first.

Where you’ve seen it

A marketplace stores product attributes that vary by category (screen size for phones, fabric for shirts) in attributes jsonb, with a GIN index so WHERE attributes @> '{"brand": "Acme"}' is fast, while price, stock and category stay as real typed columns.

Words you’ll hear

json vs jsonb
Text stored as-is vs parsed binary with indexing support.
-> and ->>
Get a field as JSON (->) or as text (->>).
@>
Containment: does the document contain this JSON fragment?
GIN index
Index type that makes containment and key-existence queries on jsonb fast.

Visual diagram

Loading interactive diagram

Theory & example queries

Querying jsonb

-> returns a JSON value (attributes -> 'dimensions'), ->> returns text (attributes ->> 'brand'), and #> / #>> follow a path (attributes #>> '{dimensions,width}'). Cast text results to the type you need: (attributes ->> 'weight_g')::int.

@> tests containment (attributes @> '{"brand": "Acme"}') and ? tests whether a key exists. A GIN index on the column (CREATE INDEX ON products USING gin (attributes)) speeds up both. For one frequently filtered key, a B-tree expression index on (attributes ->> 'brand') is smaller and faster.

Filtering on a JSON fieldQuery example
1Input dataStart from the source rows or state that the statement sees.
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  id,3  attributes ->> 'size' AS size4FROM5  products6WHERE7  category = 'shirts'8  AND attributes @> '{"brand": "Acme"}';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative matching products3 sample rows
Representative matching products
idsize
11M
42L
77S

Note: Assumes these shirt documents contain brand Acme and a text or string-convertible size field.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: ->> for text, @> for containment, GIN for indexing.

When JSON helps and when it hurts

Good fits: data whose shape varies or that you store as received (webhook payloads, third-party API responses), sparse optional attributes, and user preferences. It avoids dozens of mostly-NULL columns and constant schema changes.

Costs: no column types, NOT NULL, CHECK or foreign keys inside the document, unless you add them yourself; the planner has no statistics for keys inside JSON, so estimates (and therefore plans) can be poor; and updating one key rewrites the whole value, which is expensive for large documents. If you regularly filter, join or aggregate on a field, promote it to a real column, for example a generated column brand text GENERATED ALWAYS AS (attributes ->> 'brand') STORED.

Promoting a hot fieldQuery example
1Input dataStart from the source rows or state that the statement sees.
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1ALTER TABLE products2ADD COLUMN brand text GENERATED ALWAYS AS (attributes ->> 'brand') STORED;34CREATE INDEX ON products (brand);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/4
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command status
ALTER TABLE CREATE INDEX

Note: PostgreSQL command tags are representative. Adding and indexing the generated column may take time on a populated table and requires the column not to exist already.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Use JSON for genuinely flexible data; promote fields you query constantly.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Separate stable fields from flexible ones

Fields every row has and that you filter or join on become columns; varying or rarely queried fields can go in jsonb.

Focus at this step

price → column · fabric → jsonb

What to watch at this step
Rule
query often → column
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

PostgreSQL has two JSON types. json stores the text exactly as given, preserving spaces, key order and duplicate keys, and re-parses it on every access. jsonb stores a parsed binary form: slightly slower to write, much faster to query, supports indexes (GIN) and containment checks, but drops duplicate keys and doesn't keep key order. For almost everything, use jsonb.

Why it matters: JSON columns let you store semi-structured data, such as API payloads, settings or attributes that differ per product, without a schema change for every new field. Overusing them loses types, constraints and good query plans, so knowing when JSON fits is a common design question.

When to reach for it

  • Storing webhook and API payloads as received
  • Category-specific product attributes
  • User preferences and feature settings

When to avoid or be careful

  • Putting core fields (price, status, foreign keys) inside JSON
  • The json type when you'll query the data
  • Large documents that are updated one key at a time very frequently

Columns vs jsonb vs a separate attributes table

Regular columns
Best for: Fields every row has and queries rely on

Strengths: Types, constraints, statistics and simple indexes.

Watch out: A schema change for every new field.

jsonb column
Best for: Varying, optional or externally defined attributes

Strengths: Flexible, indexable with GIN, no migrations for new keys.

Watch out: Weak validation, poor planner estimates, whole-value rewrites.

Key-value attributes table (EAV)
Best for: Very dynamic attributes needing per-attribute rows

Strengths: Fully relational and joinable.

Watch out: Awkward, slow queries for multi-attribute filters.

Interview signals & numbers to know

When this topic comes up

  • “json vs jsonb”
  • “Should we store this as JSON?”
  • Varying attributes per product
  • Slow queries filtering on JSON fields
  • GIN index

Benchmarks & rules of thumb

->> -
returns text
@> -
containment operator
GIN -
index type for jsonb

Common mistakes & follow-ups

Common interview mistakes

  • Using json instead of jsonb and getting slow queries with no index support.
  • Comparing attributes ->> 'qty' > '10' as text, which sorts '9' after '10'; cast to a number first.
  • Hiding a foreign key inside JSON, where the database can't enforce it.

Likely interviewer follow-ups

  • What's the difference between json and jsonb in PostgreSQL?
  • How would you index queries that filter on a JSON field?
  • When would you move a field out of JSON into its own column?
Interview tip: Answer json vs jsonb in one sentence, then give your rule of thumb (stable, queried fields become columns; flexible ones go in jsonb with a GIN index). The rule matters more to interviewers than the operators.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Working with JSON & JSONB Data Types with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Materialized Views & Concurrent Refresh Strategies
Next topic
Querying JSON Objects & Arrays (->, ->>, #>, @>, jsonb_each, jsonb_array_elements)