Sub topic 10
Semi-structured data with jsonb
This chapter assumes you can write SELECT, INSERT and CREATE TABLE, and that you know what an index is. It covers the jsonb type: how it differs from json, the operators you use daily, how to index it, and where it causes problems.
json versus jsonb
PostgreSQL has two JSON types. Both check that the input is valid JSON, but they store it differently.
| Property | json | jsonb |
|---|---|---|
| Storage | Exact copy of the input text | Decomposed binary format |
| Whitespace and key order | Preserved | Not preserved |
| Duplicate keys | Kept | Last value wins |
| Indexing (GIN) | No | Yes |
| Speed on read | Reparsed on every access | Fast, no reparsing |
| Speed on write | Slightly faster | Slightly slower (conversion) |
Use jsonb unless you must keep the original text byte for byte, for example when you store a signed webhook body. The rest of this chapter uses jsonb.
SELECT '{"b": 1, "a": 2, "a": 3}'::json AS as_json,
'{"b": 1, "a": 2, "a": 3}'::jsonb AS as_jsonb;The json column returns the text unchanged. The jsonb column returns {"a": 3, "b": 1}: the duplicate key keeps its last value, and keys are reordered (shorter keys first, then by byte order).
Storing and extracting values
This table is the starting point for the examples that follow.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload jsonb NOT NULL
);
INSERT INTO events (payload) VALUES ('{"type": "signup", "plan": "pro"}');
SELECT payload ->> 'plan' AS plan
FROM events
WHERE payload @> '{"type": "signup"}';The query returns pro. Two operators appear here, and the difference between them matters:
->returns ajsonbvalue. Use it to keep navigating, as inpayload -> 'user' -> 'address'.->>returnstext. Use it at the end of a path when you want a SQL value.
The main extraction operators are:
| Operator | Meaning | Example result type |
|---|---|---|
| `->` key or index | Element as jsonb | jsonb |
| `->>` key or index | Element as text | text |
| `#>` path array | Nested element as jsonb | jsonb |
| `#>>` path array | Nested element as text | text |
A path such as payload #>> '{user,address,city}' is shorter than chained -> operators. A missing key returns SQL NULL, not an error.
Casting extracted values
->> always gives you text, so you cast it to the type you need:
SELECT (payload ->> 'amount')::numeric AS amount
FROM events
WHERE payload ->> 'type' = 'purchase';The parentheses are required. The :: operator binds tighter than ->>, so payload ->> 'amount'::numeric casts the string literal 'amount' to numeric and fails.
If one row holds "amount": "abc", the cast raises invalid input syntax for type numeric and the whole query fails. Semi-structured data has no type guarantee on its values, so this is a common production error.
JSON null versus SQL NULL
A JSON null is a value. A missing key is the absence of a value. They behave differently:
SELECT '{"a": null}'::jsonb -> 'a' AS json_null_arrow,
'{"a": null}'::jsonb ->> 'a' AS json_null_text,
'{}'::jsonb -> 'a' AS missing_arrow,
jsonb_typeof('{"a": null}'::jsonb -> 'a') AS type_of_null;-> on the JSON null returns the jsonb value null, which is not SQL NULL. ->> returns SQL NULL for both cases. Only -> on the missing key returns SQL NULL. jsonb_typeof returns the string null for the first case. To tell a JSON null from a missing key, use -> with jsonb_typeof, or test for the key with ?.
Containment and key existence
The containment operator @> asks whether the left value contains the right value, and it is the operator indexes serve best.
SELECT '{"type": "signup", "plan": "pro"}'::jsonb @> '{"plan": "pro"}' AS has_plan,
'{"tags": ["a", "b", "c"]}'::jsonb @> '{"tags": ["a"]}' AS has_tag,
'{"type": "signup"}'::jsonb ? 'type' AS has_key;All three results are true. Containment matches nested structures and array elements regardless of position. The ? operator tests whether a text string exists as a top-level key (or as a string element of a top-level array). ?| tests for any of several keys and ?& for all of them.
Modifying documents
jsonb values are immutable. Operators and functions return a new value, which you assign back with UPDATE.
UPDATE events
SET payload = jsonb_set(payload, '{plan}', '"team"')
WHERE payload @> '{"type": "signup"}';
UPDATE events SET payload = payload || '{"source": "web"}'; -- add or overwrite keys
UPDATE events SET payload = payload - 'source'; -- delete a keyThe third argument of jsonb_set is itself jsonb, so a string needs inner double quotes: '"team"'. Passing 'team' raises an invalid JSON error.
You should know a storage detail here. PostgreSQL rewrites the whole document when you change one key. Large documents that are updated often produce a lot of write traffic and table bloat. If a few keys change often, make them real columns.
Indexing jsonb
Without an index, a @> filter scans the whole table. A GIN index fixes that:
CREATE INDEX events_payload_idx ON events USING gin (payload);The default operator class, jsonb_ops, indexes every key and value. It supports @>, ?, ?| and ?&. The alternative, jsonb_path_ops, is smaller and faster for @>, but it supports only containment and the jsonpath operators @? and @@:
CREATE INDEX events_payload_path_idx ON events USING gin (payload jsonb_path_ops);GIN indexes do not help ->> comparisons such as payload ->> 'plan' = 'pro'. For a single frequently filtered key, use an expression index with B-tree:
CREATE INDEX events_plan_idx ON events ((payload ->> 'plan'));The query must use the same expression, payload ->> 'plan', for the planner to use this index.
Expanding documents into rows
Functions such as jsonb_each, jsonb_array_elements and jsonb_to_recordset turn documents into rows. In the other direction, jsonb_build_object and jsonb_agg build documents from rows.
SELECT jsonb_array_elements('["a", "b"]'::jsonb) AS tag;
SELECT jsonb_build_object('id', id, 'type', payload ->> 'type') AS summary
FROM events;When jsonb is the right choice
jsonb suits payloads from external systems, per-row optional attributes, and audit or event data. It is a poor fit for core fields such as prices or foreign keys, for three reasons:
- It has no per-key type enforcement. A
CHECKconstraint can only verify structure, for exampleCHECK (jsonb_typeof(payload) = 'object'). - It has no foreign keys into the document.
- The planner keeps no per-key statistics, so its row estimates for filters on jsonb values are often poor.
Exercise
A table events(payload jsonb) has a GIN index with the default operator class. Does WHERE payload ->> 'plan' = 'pro' use that index? What would you change to make it fast, and what query form would you use for the GIN index instead?
Show answer
No. GIN with jsonb_ops supports @>, ?, ?| and ?&, not ->> comparisons. Either create a B-tree expression index, CREATE INDEX ON events ((payload ->> 'plan')), and keep the same expression in the query, or rewrite the filter as WHERE payload @> '{"plan": "pro"}' so the GIN index applies.
Exercise
Why does SELECT payload ->> 'amount'::numeric FROM events fail, and how do you fix it?
Show answer
The :: cast binds tighter than ->>, so PostgreSQL tries to cast the literal 'amount' to numeric, which is invalid. Add parentheses: (payload ->> 'amount')::numeric.