Skip to content
mentoor

Topic 1 of 5 · 4 min read

JSONB columns and their indexes

Goal: Decide which fields of a JSON payload become columns, write a containment query and add the GIN index it uses.

Put the fields you filter, join and constrain on into real columns, and keep the rest of a payload in a JSONB column with a GIN index for the queries that reach into it. JSONB is a good home for data whose shape you do not control. It is a poor home for data you query every day.

Check yourself · 1 of 3

Which column type should hold a webhook payload you want to search inside with an index?

Choose one answer

Why it matters

Apps now save a lot of JSON: webhook bodies, user settings, and structured output from Claude, ChatGPT or Gemini. The easy move is one payload jsonb column. It works until someone asks for "all orders with status refunded", and every query has to dig into the document with no types, no foreign keys and no NOT NULL.

How to do it

  1. Sort the fields. A field you filter on, sort by, join on or must always have becomes a column. A field that is optional, varies by source, or is only displayed stays in JSONB.
  2. Use jsonb, not json. jsonb is stored parsed, supports indexes and operators. json keeps the raw text and re-parses it on every read.
  3. Query with containment. The @> operator asks "does this document contain this fragment?" and can use an index.
  4. Index it. CREATE INDEX ON events USING GIN (payload jsonb_path_ops) is smaller and faster for @> than the default operator class, which also supports key-existence operators.
  5. Index one hot key instead when you only ever query a single path: a B-tree on the expression ((payload->>'customer_id')).
  6. Guard the shape. Add a CHECK constraint (for example jsonb_typeof(payload) = 'object'), or validate in the app before insert. A model's JSON output is a guess in the right format, not a contract.

Before and after

-- Weak: filter on an extracted text value, no index can help
SELECT id FROM events WHERE payload->>'type' = 'refund';
-- Better: type is a real column, the rest stays flexible
ALTER TABLE events ADD COLUMN type text GENERATED ALWAYS AS (payload->>'type') STORED;
CREATE INDEX ON events (type);
CREATE INDEX ON events USING GIN (payload jsonb_path_ops);
SELECT id FROM events WHERE payload @> '{"items":[{"sku":"A-17"}]}';

What goes wrong

  • Everything in one blob. You lose types and constraints, and every reader re-invents the parsing.
  • A GIN index on a column you query with ->>. The index serves @> and similar operators, not an extracted-text comparison, so the planner ignores it.
  • Updating one key rewrites the whole document. A hot counter inside a large JSONB value creates a new row version each time. Put it in its own column.
  • Trusting model output. A field the model sometimes returns as a string and sometimes as a number breaks the first query that casts it.

Examples

Hybrid table for webhook events

CREATE TABLE webhook_events (
  id bigserial PRIMARY KEY,
  provider text NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now(),
  event_type text GENERATED ALWAYS AS (body->>'type') STORED,
  body jsonb NOT NULL CHECK (jsonb_typeof(body) = 'object')
);
CREATE INDEX ON webhook_events (provider, event_type, received_at);

The three fields every query uses are plain columns. The full body stays available for debugging and for fields nobody has needed yet.

Containment versus extraction

-- Uses a GIN index on tags
SELECT id FROM posts WHERE meta @> '{"tags":["sql"]}';

-- Cannot use that GIN index
SELECT id FROM posts WHERE meta->>'lang' = 'en';

Check with EXPLAIN which form the planner can serve before adding an index.

Key points

  • Fields you filter, join, sort or require belong in real columns; optional or source-specific fields can stay in JSONB.
  • Use jsonb rather than json: it is parsed on write and supports indexes and containment.
  • The containment operator @> is what a GIN index on a jsonb column accelerates; ->> text comparisons need an expression index instead.
  • jsonb_path_ops makes a smaller, faster GIN index for containment but does not support key-existence operators.
  • Updating any key rewrites the whole JSONB value, so frequently changing fields should not live inside it.
  • Model output saved as JSON still needs validation before insert, because its shape is not guaranteed.

Common mistakes

  • Storing an entire entity in one JSONB column and filtering on it with ->> in every query.
  • Creating a GIN index and assuming it speeds up equality tests on ->> expressions.
  • Keeping a frequently updated counter or status inside a large JSONB document.
  • Inserting model-generated JSON without checking that required keys exist and have the expected types.

Check yourself · 2 of 3

A query filters on payload->>'status' = 'paid' in 90 percent of requests. What is the best change?

Choose one answer

Check yourself · 3 of 3

Which query can use a GIN index created with USING GIN (doc jsonb_path_ops)?

Choose one answer

Practice items, not counted towards your mastery.

Start here