JSONB stores JSON in a decomposed binary format—efficient storage and indexing. Ideal for flexible attributes, feature flags, and event payloads alongside relational columns.
JSON vs JSONB
CREATE TABLE events (
id BIGSERIAL PRIMARY KEY,
kind TEXT NOT NULL,
payload JSONB NOT NULL
);
INSERT INTO events (kind, payload)
VALUES ('signup', '{"plan": "pro", "referrer": "newsletter"}');Use JSONB almost always; plain JSON preserves whitespace and key order but is slower to query.
Practice: Run in psql or DB Fiddle (PostgreSQL). Use your practice database from the workflow lesson.
Operators and paths
SELECT payload->>'plan' AS plan
FROM events
WHERE payload @> '{"plan": "pro"}';
SELECT payload #>> '{referrer}' AS referrer
FROM events;
GIN indexes (preview)
CREATE INDEX idx_events_payload ON events USING GIN (payload);GIN indexes accelerate containment (@>) and path queries—add when JSONB filters appear in EXPLAIN plans.
Important interview questions and answers
- Q: -> vs ->>?
A: -> returns JSON; ->> returns text—use ->> for string comparisons. - Q: JSONB mutability?
A: Use jsonb_set for partial updates without rewriting the whole document in application code.
Self-check
- Which type should you default to for queryable JSON?
- What operator checks JSON containment?
Tip: Add a GIN index when JSONB filters show up in hot EXPLAIN plans.
Interview prep
- ->> operator?
Extracts JSON field as text.
- @> operator?
Tests JSON containment.