PostgreSQL is one of the best places to store semi‑structured data because it gives you two native JSON types:
json— stores JSON as text (preserves whitespace and key order).jsonb— stores JSON in a binary, decomposed form (optimized for querying and indexing).
In practice, jsonb is the default choice for application data you want to query. Use json only when you truly need to preserve the original JSON text exactly as inserted (including formatting).
JSON vs JSONB (the differences that matter)
Storage & normalization
jsonstores the raw JSON string. Every query must parse it.jsonbstores a normalized binary format.- Key order is not preserved.
- Whitespace is not preserved.
- Duplicate object keys are normalized (Postgres keeps the last value for a duplicated key).
Performance
- Reads/filters/containment queries are usually faster with
jsonb. jsonbsupports GIN indexing, which is the big win for performance.- Writes/updates can be slightly heavier with
jsonbbecause of the normalization work and index maintenance.
Recommended rule of thumb
- Use
jsonbfor almost everything. - Use normal columns for fields you always filter/sort/join on.
- Keep JSON for “extra attributes” that change often or vary by record.
Modeling pattern: columns + jsonb (best of both worlds)
Example: store stable fields as columns, flexible fields as jsonb.
create table events (
id bigserial primary key,
user_id bigint not null,
event_type text not null,
created_at timestamptz not null default now(),
payload jsonb not null
);
Then user_id, event_type, created_at stay cheap to query, while payload holds extra shape‑shifting data.
Querying jsonb: operators you’ll actually use
Assume payload looks like:
{
"device": { "os": "ios", "model": "iPhone15,2" },
"plan": "pro",
"tags": ["remote", "performance"],
"meta": { "utm": { "source": "twitter" } }
}
1) Extract values: -> and ->>
->returns JSON/JSONB->>returns text
select
payload->'device' as device_json,
payload->'device'->>'os' as os_text,
payload->>'plan' as plan
from events;
For nested paths, #> (json) and #>> (text) are handy:
select payload #>> '{meta,utm,source}' as utm_source
from events;
2) Containment: @> (the “workhorse” operator)
Containment checks whether the left JSON contains the right JSON.
select *
from events
where payload @> '{"plan":"pro"}';
Nested containment works too:
select *
from events
where payload @> '{"device":{"os":"ios"}}';
3) Key existence: ?, ?|, ?&
-- does payload have key "device"?
select *
from events
where payload ? 'device';
-- does payload have ANY of these keys?
select *
from events
where payload ?| array['device','meta','plan'];
-- does payload have ALL of these keys?
select *
from events
where payload ?& array['device','meta'];
4) Updating jsonb
Append/merge objects:
update events
set payload = payload || '{"debug":true}'::jsonb
where id = 1;
Set a nested path:
update events
set payload = jsonb_set(payload, '{device,os}', '"android"', true)
where id = 1;
Indexing jsonb (so queries stay fast)
JSONB can be very fast, but only if you index based on how you query it.
Strategy 1: GIN index on the whole jsonb column
If you do lots of @> containment or key existence queries, start here:
create index events_payload_gin on events using gin (payload);
This uses the default GIN operator class (jsonb_ops), which supports many operators.
#### Smaller/faster (when you mostly use @>)
If your queries are mostly containment (@>), you can use jsonb_path_ops:
create index events_payload_gin_path on events using gin (payload jsonb_path_ops);
Tradeoff: this index is usually smaller and faster for @>, but it supports fewer query patterns than the default.
Strategy 2: Expression indexes for specific fields (BTREE)
If you filter/sort on a single JSON field often, use an expression index:
create index events_plan_idx on events ((payload->>'plan'));
Now this becomes index‑friendly:
select *
from events
where payload->>'plan' = 'pro';
For numeric comparisons, cast:
create index events_amount_idx on events (((payload->>'amount')::numeric));
select *
from events
where (payload->>'amount')::numeric >= 100;
For nested paths:
create index events_device_os_idx on events ((payload #>> '{device,os}'));
Strategy 3: Partial indexes (when only some rows have a key)
If only some records have a property, index only those rows:
create index events_utm_source_idx
on events ((payload #>> '{meta,utm,source}'))
where payload #>> '{meta,utm,source}' is not null;
This keeps the index smaller and cheaper to maintain.
Strategy 4: Generated columns (best for “promoting” a JSON field)
When a JSON field becomes important enough, you can “promote” it to a generated column and index it like normal:
alter table events
add column plan text generated always as (payload->>'plan') stored;
create index events_plan_generated_idx on events (plan);
This keeps your application payload flexible, while letting Postgres optimize common access paths.
How to verify your index is actually used
Don’t guess—measure:
explain (analyze, buffers)
select *
from events
where payload @> '{"plan":"pro"}';
Look for:
Bitmap Index Scanon your GIN index (common for@>)Index Scanon expression indexes- lower buffer reads and lower total runtime
Practical guidelines (so you don’t regret JSONB later)
- Don’t put everything in jsonb. If you always filter/sort/join on a field, make it a column.
- Avoid giant arrays in JSONB if you need to query inside them frequently—consider a join table.
- GIN indexes are powerful but not free: they can get large and slow down writes. Use them where it matters.
- Prefer expression indexes for “one field, very frequent query”.
- Prefer partial indexes when only some rows have that field.
Cheat sheet
- Prefer:
jsonb - Workhorse query:
payload @> '{"key":"value"}' - Whole‑doc index:
USING gin (payload) - Fast containment index:
USING gin (payload jsonb_path_ops) - Hot field index:
create index ... on table ((payload->>'field')) - Nested hot field:
create index ... on table ((payload #>> '{a,b,c}'))
If you tell me your real table structure and your top 3 JSON queries, I can recommend the exact index set (and which ones to avoid to keep writes fast).
