skip to content

json and jsonb

a document in a column. ->, ->>, @>, jsonpath, JSON_TABLE, and why jsonb won.

address
everything.types.jsonb
part
part 6, types and values
chapter
chapter 9 of 11
reading time
8 min

json stores the text you gave it; jsonb parses it into a binary tree: keys sorted, duplicates gone, whitespace dropped, and every operator available. use jsonb.

-> gets a value as jsonb, ->> as text, #> follows a path. @> asks "does it contain this", jsonpath (@?, jsonb_path_query) asks anything. a GIN index makes containment fast. and a key you filter on every day is a column that hasn't been promoted yet.

the picture

you know how an API hands you a blob of json, and the fastest thing is to store it as it came? postgres lets you, twice over. json keeps the exact text, like a photocopy. jsonb reads it and files it, like a clerk who retypes the form into a neat card index: tidier, searchable, and the original handwriting is gone.

typevaluebytes
json{"b": 1, "a": 2, "a": 3}30
jsonb{"a": 3, "b": 1}44
(2 rows)
real output, postgres 18.6 (PGlite 0.5.12) · jsonb
the same text into both types. json keeps the spaces, the order and both "a" keys. jsonb keeps one "a", the last one, sorts the keys, and takes more bytes for this small document, because it stores offsets that make lookups fast.

json has to reparse the text for every operation, and it has no equality operator at all (json = json is an error). jsonb has equality, containment, indexing and the rest. the only reasons left for json are keeping duplicate keys or the exact key order, which is a promise the json standard never made anyway.

sqlempty db
SELECT '{"a": 1, "b": 2}'::jsonb = '{"b": 2, "a": 1}'::jsonb AS same_object,
       '{"price": 1.50}'::jsonb ->> 'price'                AS keeps_digits;
output, from postgres 18.6
SELECT 1
same_objectboolkeeps_digitstext
t1.50
(1 row)

(numbers are stored as numeric, so 1.50 stays 1.50.)

getting values out

the events table has a props jsonb column. event 26 is one of the ones with a nested utm object:

sqldb=events
SELECT props FROM events WHERE id = 26;
output, from postgres 18.6
SELECT 1
propsjsonb
(1 row)
operator =
props.sql
  1. 1SELECT props -> 'utm' AS result, pg_typeof(props -> 'utm') AS type FROM events WHERE id = 26;
the result for ->
resultjsonbtyperegtype
{"source": "search", "campaign": "spring"}jsonb
(1 row)

-> takes a key and gives jsonb back: still json, quotes and all.

real output, postgres 18.6 (PGlite 0.5.12) · jsonb
six operators on that one row. pick one and watch the result type. arrows return jsonb (single) or text (double); @> and @? return a boolean.

the type matters as soon as you compare or compute. ->> gives text, so a number has to be cast before arithmetic, and a json null and a missing key both come back as SQL NULL:

predict the output
sql
SELECT count(*) FILTER (WHERE props -> 'device' IS NULL)  AS arrow_null,
       count(*) FILTER (WHERE props ->> 'device' IS NULL) AS text_null
FROM events;
sqldb=events
SELECT count(*) FILTER (WHERE props -> 'device' IS NULL)   AS missing_key,
       count(*) FILTER (WHERE props -> 'device' = 'null')  AS json_null,
       count(*) FILTER (WHERE props ->> 'device' IS NULL)  AS either
FROM events;
output, from postgres 18.6
SELECT 1
missing_keyint8json_nullint8eitherint8
7497251474
(1 row)

containment and jsonpath

@> is the workhorse: does the left document contain the right one, at any depth? and there's jsonpath, a small query language for json: @? asks whether a path finds anything, jsonb_path_query returns what it finds:

sqldb=events
SELECT count(*) FILTER (WHERE props @> '{"utm": {"source": "newsletter"}}')     AS contains,
       count(*) FILTER (WHERE props @? '$.utm ? (@.source == "newsletter")')   AS jsonpath
FROM events;
SELECT jsonb_path_query_array('{"items": [{"sku": "A", "qty": 2}, {"sku": "B", "qty": 5}]}', '$.items[*] ? (@.qty > 3).sku') AS big_orders;
output, from postgres 18.6
#1 · SELECT 1
containsint8jsonpathint8
832832
(1 row)
#2 · SELECT 1
big_ordersjsonb
["B"]
(1 row)

GIN indexes both. there are two operator classes, and they trade size for reach. the default, jsonb_ops, indexes every key and every value as separate entries; jsonb_path_ops indexes a hash of each path-to-a-value, which is smaller and more selective but can only answer containment:

table335 pages
gin (props)38 pages
gin (props jsonb_path_ops)25 pages
real output, postgres 18.6 (PGlite 0.5.12) · jsonb
pages for the events table and two GIN indexes on its props, built on 25,000 rows. the path_ops index is about two thirds the size of the default.
index =
WHERE =
indexed.sql
  1. 1SELECT count(*) FROM events WHERE props @> '{"utm": {"source": "newsletter"}}';
the result for jsonb_ops | @>
countint8
832
(1 row)
the plan

the default index serves @>.

real output, postgres 18.6 (PGlite 0.5.12) · jsonb
two indexes, two questions, four real plans. pick an index and an operator. the default index serves @> and ?; jsonb_path_ops serves @> and falls back to a seq scan for ?.

neither helps props ->> 'device' = 'ios': that's an expression, and it wants an expression index on (props ->> 'device'), or a rewrite to props @> '{"device": "ios"}'. GIN has the inside story, and index types the overview.

building json, and taking it apart

the SQL standard caught up with json in two steps. postgres 16 pg 16+ added the SQL/JSON constructors, JSON_OBJECT, JSON_ARRAY and their aggregates, with standard NULL handling:

sqlempty db
SELECT JSON_OBJECT('id': 42, 'name': 'Ada', 'email': NULL)               AS with_nulls,
       JSON_OBJECT('id': 42, 'email': NULL ABSENT ON NULL)                AS absent_on_null,
       JSON_ARRAY(1, 'two', NULL, true)                                   AS array_skips_null;
output, from postgres 18.6
SELECT 1
with_nullsjsonabsent_on_nulljsonarray_skips_nulljson
{"id" : 42, "name" : "Ada", "email" : null}{"id" : 42}[1, "two", true]
(1 row)

(the older postgres functions, jsonb_build_object and friends, still work and return jsonb.) and postgres 17 pg 17+ added JSON_TABLE, which goes the other way: a path picks the rows, and each column gets a path and a type.

lineskuqtypricegift
1KIT-0001249.00f
2AUD-00051129.99t
(2 rows)
real output, postgres 18.6 (PGlite 0.5.12) · jsonb
an order document's items array, turned into rows by JSON_TABLE. each column is typed, line numbers the rows, and the missing gift key falls back to its DEFAULT.
sqlempty db
SELECT jt.*
FROM JSON_TABLE(
  '{"order": 1042, "items": [{"sku": "KIT-0001", "qty": 2, "price": 49.00},
                             {"sku": "AUD-0005", "qty": 1, "price": 129.99, "gift": true}]}',
  '$.items[*]'
  COLUMNS (line FOR ORDINALITY, sku text PATH '$.sku', qty int PATH '$.qty',
           price numeric(10,2) PATH '$.price', gift boolean PATH '$.gift' DEFAULT false ON EMPTY)
) AS jt
ORDER BY jt.line;
output, from postgres 18.6
SELECT 2
lineint4skutextqtyint4pricenumericgiftbool
1KIT-0001249.00f
2AUD-00051129.99t
(2 rows)

when a key should be a column

jsonb is right for data whose shape you don't control or that varies per row: an API payload, event properties, per-category product attributes. it's wrong for data you query the same way every day. signs that a key wants to be a column:

  • it's in a WHERE or a join on every hot query;
  • you need a constraint on it (NOT NULL, a foreign key, a CHECK);
  • you need statistics on it: the planner has none for a key inside jsonb, so its row estimates are guesses (pg_stats).

the halfway house is a generated column: device text GENERATED ALWAYS AS (props ->> 'device') keeps the document as the source of truth and gives the key a name and a type. a STORED one can be indexed and constrained like any column.

keylines

  • jsonb parses and normalises; json keeps the text. use jsonb.
  • -> returns jsonb, ->> returns text; #> and #>> take a path.
  • @> and jsonpath (@?) search documents; GIN indexes them, path_ops smaller but containment only.
  • JSON_OBJECT and JSON_ARRAY are in 16, JSON_TABLE in 17.
  • a key you filter, constrain or join on every day wants to be a column.