Working with JSON & JSONB Data Types
Store semi-structured documents with JSON/JSONB and know the trade-offs.
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
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.
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
SELECT id, attributes ->> 'size' AS sizeFROM productsWHERE category = 'shirts' AND attributes @> '{"brand": "Acme"}';PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative matching products3 sample rows
| id | size |
|---|---|
| 11 | M |
| 42 | L |
| 77 | S |
Note: Assumes these shirt documents contain brand Acme and a text or string-convertible size field.
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.
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
ALTER TABLE productsADD COLUMN brand text GENERATED ALWAYS AS (attributes ->> 'brand') STORED;CREATE INDEX ON products (brand);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Representative command status
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.
Key takeaway: Use JSON for genuinely flexible data; promote fields you query constantly.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
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.
price → column · fabric → jsonb
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
Strengths: Types, constraints, statistics and simple indexes.
Watch out: A schema change for every new field.
Strengths: Flexible, indexable with GIN, no migrations for new keys.
Watch out: Weak validation, poor planner estimates, whole-value rewrites.
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?
Knowledge check
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.