How-To Guide

How to Query JSONB in PostgreSQL

Store flexible documents in JSONB, index the keys you query, use containment and path operators safely, and avoid the performance traps of schemaless data.

On this page

  1. Introduction
  2. Choose JSONB and keep a schema
  3. Learn the operators
  4. Index the access patterns
  5. Update documents deliberately
  6. Validate and version
  7. Measure and avoid traps
  8. Test with realistic documents
  9. Conclusion

Introduction

PostgreSQL’s JSONB type stores JSON in a decomposed binary form that supports indexing and operators. It is useful for attributes that vary by product, tenant, or event type, such as feature-specific settings, third-party payloads, or audit metadata. It is not a license to avoid schema design. Stable fields that are filtered, joined, or constrained usually belong in relational columns; variable attributes can live in JSONB.

The performance difference between a well-indexed JSONB query and a naive one is large. A containment query can use a GIN index and return in milliseconds; an expression that casts or transforms the column can force a sequential scan over millions of rows. This tutorial covers the operators, indexes, updates, validation, and measurement needed to use JSONB without turning the database into an opaque document store.

Choose JSONB and keep a schema

Use JSONB when the shape is genuinely variable and the application benefits from storing it as a document. Keep identifiers, foreign keys, timestamps, status, and fields used in joins or constraints as normal columns. Duplicating a status inside JSONB and in a column creates two sources of truth and eventual inconsistency.

Validate the document at the write boundary. A JSON Schema validator, Pydantic model, or application-level schema ensures required keys and types before the row is stored. PostgreSQL can check that a value is valid JSON, but it cannot enforce your business schema without expensive constraints. Store a schema_version field so readers can handle old and new shapes during migrations.

CREATE TABLE events (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  type text NOT NULL,
  occurred_at timestamptz NOT NULL,
  payload jsonb NOT NULL,
  schema_version integer NOT NULL DEFAULT 1
);

Learn the operators

The containment operator @> checks whether the left JSONB contains the right structure. It is the basis for many GIN-indexed queries:

SELECT id, payload
FROM events
WHERE payload @> '{"tenant_id": "t-42", "kind": "purchase"}';

The ? operator checks whether a top-level key or array element exists, ?| checks any of a list, and ?& checks all. The -> operator returns JSONB by key, while ->> returns text. Use ->> when comparing to a string; use -> when passing a nested document to another JSONB operator.

SELECT payload->>'currency' AS currency,
       (payload->>'total')::numeric AS total
FROM events
WHERE payload->>'kind' = 'purchase'
  AND occurred_at >= now() - interval '7 days';

Casting a value inside the query is common, but it can prevent index use. If the cast is on the extracted value and the predicate matches an expression index, the planner can still use it. If the cast wraps the indexed expression differently, it cannot.

For complex paths, jsonb_path_query and jsonb_path_exists support SQL/JSON path expressions with filters and variables:

SELECT jsonb_path_query(payload, '$.items[*] ? (@.quantity > $min)', '{"min": 2}');

The path string is code-like; do not build it by concatenating user input. Keep path expressions fixed and pass values through the variables argument or bind parameters.

Index the access patterns

A GIN index on the whole column accelerates containment and key-existence queries:

CREATE INDEX events_payload_gin ON events USING gin (payload jsonb_path_ops);

jsonb_path_ops is smaller and faster for @> queries but supports fewer operators than the default jsonb_ops. Choose based on the queries you actually run. A GIN index has write cost: every insert and update maintains it. Do not add one unless a measured query needs it.

For a hot path that extracts one field, an expression index can be smaller and faster:

CREATE INDEX events_tenant_idx ON events ((payload->>'tenant_id'));

The query must use the same expression, including the same operator and cast, for the planner to match the index. Wrapping it in a function or changing the cast can break the match. Verify with EXPLAIN (ANALYZE, BUFFERS) that the index is used and the row estimate is reasonable.

Update documents deliberately

jsonb_set updates a path and returns a new document:

UPDATE events
SET payload = jsonb_set(payload, '{status}', '"processed"', true)
WHERE id = $1;

The true argument creates the path if it is missing. For removing a key, use the - operator. Every update rewrites the whole JSONB value and creates a new row version, so updating a large document for a small field is expensive. If a field is updated frequently, promote it to a column. Watch row size and TOAST; very large documents are stored out of line and have their own read costs.

Validate and version

JSONB accepts any valid JSON, including arrays, scalars, and deeply nested structures. Add a check constraint for the top-level type when the contract requires an object:

ALTER TABLE events
  ADD CONSTRAINT payload_is_object CHECK (jsonb_typeof(payload) = 'object');

For schema evolution, store a version and make readers tolerate old shapes. Migrate documents in batches only when necessary; a full rewrite of millions of large documents is a major operation. Prefer additive changes and defaults at read time.

Measure and avoid traps

The most common performance trap is a query that looks indexed but is not. Run EXPLAIN (ANALYZE, BUFFERS) with real data. Check for sequential scans, high rows removed by filter, and index-only scans that are not actually index-only. A GIN index can be large; monitor its size and write amplification.

Another trap is treating JSONB as a place to hide relationships. Joining on a JSONB field is possible but usually slower and less clear than a normalized foreign key. If a value is used in joins, constraints, or frequent filters, model it as a column.

Finally, do not return entire documents to clients by default. A JSONB payload can contain internal fields, personal data, or large nested objects. Select the fields the API contract exposes and apply authorization before serialization.

Test with realistic documents

Test containment queries with documents that have the key, lack the key, have a different type, and have nested arrays. Test the expression index with the exact query used in production. Test updates on a document at the maximum expected size and measure the row version growth. A test with three tiny documents does not reveal TOAST or index behavior.

For migrations, keep a corpus of old documents and run the reader against them. Assert that missing optional fields get the documented default and that unknown fields do not break serialization.

Conclusion

JSONB is a powerful tool for variable data when it is used with a contract and an index plan. Keep stable fields relational, validate documents on write, use containment and path operators with bound values, index the actual access patterns, and update small fields carefully. Measure the plan with production-sized data. The result is flexible storage without the silent performance and consistency problems of an ungoverned document store.

Sources: PostgreSQL JSON types, JSONB indexing, SQL/JSON path.

FAQ

Should I use JSON or JSONB?
Use JSONB when you need indexing, containment queries, or efficient updates. JSON preserves the original text and key order but is slower to query and cannot use the same index types.
Does a GIN index make every JSONB query fast?
No. A GIN index helps containment and key-existence queries. A query that extracts a field and compares it may need an expression index, and a function or cast around the column can prevent index use.
Is JSONB a replacement for a schema?
No. JSONB stores arbitrary documents, but the application still needs a contract. Validate on write, version the document shape, and migrate data deliberately.

Related Examples