Code Reference

JSON & JSONB

Postgres · Reference cheat sheet

JSON & JSONB

Postgres · Reference cheat sheet


📋 Overview

json stores text as-is; jsonb stores a binary decomposed form — better for indexing and containment queries. Prefer jsonb for operational query patterns.

🔧 Core concepts

TypeTrait
jsonPreserves whitespace/key order; reparsed
jsonbDedupes keys; indexable; usually preferred
Operator / fnRole
-> / ->>Get object field (json / text)
#> / #>>Path extract
@>Contains
? / `?/?&`
jsonb_setModify
GIN indexAccelerate @> / path ops

💡 Examples

Query fields:

SELECT payload->>'event'
FROM events
WHERE payload @> '{"type":"signup"}';

GIN index:

CREATE INDEX CONCURRENTLY events_payload_gin
  ON events USING GIN (payload jsonb_path_ops);

Update key:

UPDATE users
SET prefs = jsonb_set(prefs, '{theme}', '"dark"', true)
WHERE id = 42;

⚠️ Pitfalls

  • Unindexed payload->>'x' = on large tables seq-scans — express as jsonb ops + GIN when possible.
  • Turning everything into JSONB abandons relational constraints — hybrid carefully.
  • json vs jsonb equality and duplicate-key behavior differ.

On this page