Skip to content
Visual explainer 3h to learn 5 steps

JSONB & arrays

Store, query and index semi-structured JSONB data.

By Invicly Tech, , in SQL & PostgreSQL. About 8 minutes to read.

Topic 11 of 30

In short

JSONB stores JSON documents in a binary form that Postgres can query and index. It suits flexible attributes that vary per row, while array columns hold simple lists of values.

Explained simply

Tables are great when every row has the same fields. But sometimes the fields vary. A laptop has RAM and screen size, a T-shirt has size and colour. Making a column for every possible attribute would leave most cells empty.

JSONB lets one column hold a small document of key-value pairs, like {"color": "red", "size": "M"}. Each row can have different keys. Postgres still understands the contents, so you can filter, sort and index on them.

Arrays are the simpler cousin. A text[] column holds a plain list, like tags: {sale, summer, new}. They are handy for short lists of simple values that belong to one row and are not shared with other tables.

The trick is balance. Keep the important, always-present fields as normal columns with proper types and constraints. Use JSONB for the flexible extras, and arrays for small lists. That gives you structure where it matters and freedom where you need it.

Press Play on a diagram to walk through it one step at a time.

MapWorking with JSONB
attrs JSONB column
  • Extract
    • -> returns jsonb
    • ->> returns text
    • #>> takes a path
  • Test
    • @> contains
    • ? has key
  • Index
    • GIN (jsonb_ops)
    • GIN (jsonb_path_ops)
  • Arrays
    • text[] column
    • ANY(tags)
    • @> ARRAY['a']
Comparejson vs jsonb
json
  • Stored as exact text
  • Keeps whitespace, key order
  • Re-parsed on every use
  • No GIN indexing
jsonb
  • Stored parsed and binary
  • Duplicate keys removed
  • Faster to query
  • Indexable with GIN
FlowFrom a product's attributes to a fast filter
  1. 1
    Store

    attrs = {"color": "red", "size": "M"}

  2. 2
    Index

    CREATE INDEX ... USING gin (attrs jsonb_path_ops)

  3. 3
    Query

    WHERE attrs @> '{"color": "red"}'

  4. 4
    Bitmap index scan

    GIN finds matching rows directly

  5. 5
    Return rows

    No full-table scan needed

In depth

Reading nested values

-> and ->> take one key or array index. For deeper paths, chain them: data->'address'->>'city'. Or use a path: data #>> '{address,city}'. Arrays inside JSON are indexed from 0, so data->'items'->0 is the first item.

Values from ->> are text, so cast them for maths or date comparisons: (data->>'price')::numeric > 20. If a key is missing, you get NULL, not an error.

To turn a JSON array into rows, use jsonb_array_elements(data->'items') in the FROM clause. Each element becomes one row you can join and group like a normal table. jsonb_each does the same for the keys of an object.

  • a->'b'->>'c' or a #>> '{b,c}' for nested text
  • Cast ->> results: ::numeric, ::int, ::date
  • jsonb_array_elements: array to rows
  • Missing key gives NULL

Changing JSONB without rewriting it by hand

You rarely need to rebuild a document to change it. The || operator merges objects, with the right side winning: attrs || '{"color": "blue"}' sets or replaces one key. The - operator removes a key: attrs - 'color'. jsonb_set(attrs, '{dims,width}', '30') changes a nested value.

Under the hood, Postgres still writes a whole new copy of the row, because rows are never edited in place. Very large documents that change often therefore cost more to update than a few normal columns would.

MapChanging JSONB in place
attrs (JSONB)
  • || merge
    • attrs || '{"color": "blue"}'
    • Right side wins
  • - remove key
    • attrs - 'color'
  • jsonb_set
    • jsonb_set(attrs, '{dims,width}', '30')
  • Under the hood
    • A new row version is written

Indexing JSONB in practice

A GIN index on the whole column speeds up containment (@>) and key checks (?). The default operator class jsonb_ops supports all of them. jsonb_path_ops supports only @> but is smaller and faster for it.

If you filter on one field with ordinary comparisons, like price ranges, a GIN index will not help. Instead create a B-tree expression index on exactly that expression: CREATE INDEX ON products (((attrs->>'price')::numeric)). The query must use the same expression to benefit.

For arrays, a GIN index supports @> (contains), <@ (is contained by) and && (overlaps), for example WHERE tags && ARRAY['sale', 'new'].

ComparePicking a JSONB index
GIN, jsonb_ops (default)
  • Containment @>
  • Key checks like ?
  • Larger index
GIN, jsonb_path_ops
  • Containment @>
  • No key checks like ?
  • Smaller and faster for @>
B-tree expression index
  • ((attrs->>'price')::numeric)
  • Ranges and normal comparisons
  • Query must use the same expression

When JSONB is the wrong choice

JSONB gives up several safety features of columns. There are no foreign keys into a JSON field, no NOT NULL or CHECK on individual keys unless you write them by hand, and typos in key names silently create new keys. Planner statistics on JSON fields are weak, so estimates for JSON filters can be poor.

A good rule: if every row has the field, you filter or join on it often, or other tables refer to it, make it a real column. Keep JSONB for genuinely variable data, raw API payloads, and settings blobs.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Store documents in JSONB~35m
  2. 2
    Query with -> and ->> operators~35m
  3. 3
    Filter with @> containment~35m
  4. 4
    Index JSONB with GIN~35m
  5. 5
    Work with array columns~35m

Key points

  • Use ->> when comparing to text or casting: (attrs->>'price')::numeric.
  • attrs @> '{"color": "red"}' finds rows containing that key and value.
  • A GIN index makes @> and key-existence queries fast.
  • Put fields you filter and join on constantly into real columns.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
CREATE TABLE products (
  id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name  text NOT NULL,
  attrs jsonb NOT NULL DEFAULT '{}',
  tags  text[] NOT NULL DEFAULT '{}'
);
CREATE INDEX ON products USING gin (attrs);

SELECT name, attrs->>'color' AS color, (attrs->>'weight_kg')::numeric AS kg
FROM products
WHERE attrs @> '{"brand": "Acme"}'
  AND 'sale' = ANY(tags);

Saving webhook payloads and reporting on them

A payment provider sends JSON events. Step 1: store each event as received in a jsonb column so nothing is lost. Step 2: pull out the fields you need with ->> and cast them. Step 3: group like normal columns. Step 4: if this report runs often, add an expression index on the event type.

sql
CREATE TABLE events (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  received_at timestamptz NOT NULL DEFAULT now(),
  payload jsonb NOT NULL
);

SELECT payload->>'type' AS type,
       COUNT(*) AS events,
       SUM((payload->'data'->>'amount')::numeric) AS amount
FROM events
WHERE received_at >= now() - interval '1 day'
GROUP BY 1;

Line items inside an order document

An order stores items as a JSON array: [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}]. To find the total quantity per SKU across all orders, Step 1: expand the array into rows with jsonb_array_elements in a LATERAL position. Step 2: read sku and qty from each element. Step 3: group and sum.

sql
SELECT item->>'sku'               AS sku,
       SUM((item->>'qty')::int)   AS units
FROM orders o,
     jsonb_array_elements(o.doc->'items') AS item
GROUP BY 1
ORDER BY units DESC;

Quick reference

  • -> returns jsonb, ->> returns text; #> and #>> take a path like '{a,b}'
  • (doc->>'price')::numeric to compare or do maths
  • doc @> '{"k": "v"}' containment; doc ? 'k' key exists
  • doc || '{"k": 1}' set a key; doc - 'k' remove a key; jsonb_set for nested
  • jsonb_array_elements(doc->'items') turns an array into rows
  • GIN for @> and ?, B-tree expression index for one field's ranges
  • Arrays: 'x' = ANY(tags), tags @> ARRAY['x'], tags && ARRAY['x','y']

Common mistakes

  • Comparing -> output (jsonb) to plain text and getting type errors.
  • Putting everything in JSONB, losing types, constraints and foreign keys.
  • Expecting a B-tree index on the column to speed up @> queries.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which expression returns the city as text from {"address": {"city": "Oslo"}}?

Question 2

2You filter WHERE (attrs->>'price')::numeric < 20. Which index can help?

Question 3

3What does doc - 'temp' do to a jsonb value?

Question 4

4Which data is the best fit for a JSONB column?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    From products(name, attrs jsonb), list the names of products whose attrs contain color "red".

  2. Exercise 2medium

    Add the key "discontinued": true to the attrs of product 15 without touching its other keys, and return the new attrs.

  3. Exercise 3hard

    Products have tags text[]. Find the 5 most common tags across all products and create an index that speeds up "has tag X" filters.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use json or jsonb?
Use jsonb almost always. Plain json only makes sense when you must keep the exact original text, including key order and whitespace.
Can Postgres replace MongoDB?
For many apps, yes: jsonb gives document storage, indexing and querying, plus transactions and joins. Very large, schema-free workloads with heavy sharding may still suit a document database better.
Why does my JSON comparison give a type error?
-> returns jsonb, which cannot be compared to plain text or numbers directly. Use ->> to get text, then cast it if needed.

Go deeper

ShareXLinkedInWhatsApp