Sub topic 10
Semi-structured data with `jsonb`
Assume you know SELECT, INSERT, CREATE TABLE, and basic constraints. This chapter focuses on PostgreSQL's jsonb type and the operators used to store and query data whose shape can vary.
When to use `jsonb`
JSON is a text format for objects, arrays, strings, numbers, booleans, and null. PostgreSQL provides two JSON types:
jsonstores the original JSON text.jsonbparses the document and stores it in a binary form.
For most database applications, choose jsonb. It supports indexing and efficient searches. It also removes insignificant whitespace and does not preserve duplicate object keys. Use json only when preserving the exact original document matters.
A jsonb column is useful for optional attributes, event payloads, or data supplied by external systems. It should not replace ordinary columns when the database must frequently filter, join, constrain, or aggregate a value.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO events (event_type, payload)
VALUES
('signup', '{"plan": "pro", "marketing_opt_in": true}'),
('purchase', '{"order_id": 42, "total": 19.99}');Extracting values
The -> operator extracts a JSON value and keeps it as jsonb. The ->> operator extracts a value as SQL text.
SELECT
payload -> 'plan' AS plan_json,
payload ->> 'plan' AS plan_text,
payload ->> 'order_id' AS order_id_text
FROM events
WHERE event_type = 'signup';For nested objects, provide multiple keys or use #> and #>> with a path:
SELECT
payload #>> '{customer,address,city}' AS city
FROM events;The result of ->> is text, even when the JSON value looks numeric or boolean. Cast it before numeric comparisons:
SELECT *
FROM events
WHERE (payload ->> 'total')::numeric > 10;Missing keys usually produce SQL NULL. That is different from a JSON value explicitly set to null, so test the data carefully when the distinction matters.
Filtering and indexing
The @> operator tests containment. This query finds signup events whose payload contains the specified key and value:
SELECT id, payload ->> 'plan' AS plan
FROM events
WHERE payload @> '{"plan": "pro"}';A GIN index can speed up containment queries:
CREATE INDEX events_payload_gin_idx
ON events USING gin (payload);An expression index can target one frequently queried field:
CREATE INDEX events_plan_idx
ON events ((payload ->> 'plan'));How a JSONB query works
Exercise
Exercise
Write a query that returns the order_id from purchase events where the JSONB total is at least 20.
Show answer
SELECT payload ->> 'orderid' AS orderid FROM events WHERE event_type = 'purchase' AND (payload ->> 'total')::numeric >= 20;