JSON & JSONB Operators in SQL
Semi-structured inside relational — indexably
JSONB (PG) stores parsed, indexable documents: -> (object field as JSON), ->> (as text), @> (contains), ? (has key), jsonb_set/build_object for construction. GIN indexes serve containment (@>) and key probes. Relational core stays normalized; payloads carry variable shapes. Validate with CHECK (payload ? 'email') plus generated columns for hot fields.
Extract (->/->>)
-> keeps JSON, ->> yields text — project fields without fetching whole docs.
Contain (@>) + GIN
Containment probes seek GIN indexes — admin-role scans without full reads.
Build + update
jsonb_build_object/jsonb_set construct and patch — partial updates without rewrite-everything.
Promote hot fields
Generated columns + B-tree for hot JSON keys queried like columns.
1SELECT payload->>'email' AS email FROM users WHERE payload @> '{"role":"admin"}';
| how | |
|---|---|
| ada@x.com | admin match via GIN |
Containment seeks the GIN index to admin payloads only; ->> projects the email text. Fully-variable schemas stay queryable without EAV contortions.
Admin containment seek
GIN finds admin payloads only.
1SELECT payload->>'email' FROM users WHERE payload @> '{"role":"admin"}';
| how | |
|---|---|
| ada@x.com | GIN seek |
Hot key promotion
JSON agility, column speed.
1email TEXT GENERATED ALWAYS AS (payload->>'email') STORED;2CREATE INDEX ON users (email);
| artifact | effect |
|---|---|
| generated email | indexed like column |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.