JSONB in SQL

Difficulty: Intermediate

Question

What is JSONB in PostgreSQL, how is it different from JSON, and when should you use it?

Answer

JSONB is PostgreSQL's binary JSON type: the document is parsed once on write and stored in a decomposed binary form, so reads do not re-parse text and the column can be indexed with GIN or expression indexes. It lets you keep flexible, semi-structured attributes inside a normal ACID relational table. Use it for data whose shape varies, and keep core, frequently filtered fields as regular columns.

JSON vs JSONB

Aspectjsonjsonb
StorageExact input textParsed binary representation
Write costFaster (just validates)Slightly slower (converts)
Read and operatorsRe-parses on every accessFast, no re-parse
Key order and whitespacePreservedNot preserved
Duplicate keysKeptLast value wins
IndexingExpression indexes onlyGIN plus expression indexes
Containment @>Not supportedSupported

Pick json only if you must preserve the exact original text, such as storing a webhook payload for audit. Otherwise use jsonb.

Querying it

  • -> returns a JSON value, ->> returns text: attrs->>'brand'.
  • @> tests containment: attrs @> '{"brand": "boAt"}'.
  • ?, ?|, ?& test whether keys exist.
  • jsonb_set, || (merge) and - (remove key) modify documents.
  • SQL/JSON path with @? and @@, plus JSON_TABLE added in PostgreSQL 17 to turn JSON into rows.

Indexing options

  • GIN with the default jsonb_ops: supports key existence (?) and containment (@>). Good general choice.
  • GIN with jsonb_path_ops: supports @> and jsonpath operators only, but is smaller and usually faster for containment.
  • B-tree expression index on ((attrs->>'brand')): best when you always filter or sort on one known key.

When JSONB is the right tool

  • Product attributes that differ per category on an e-commerce catalog like Flipkart: a phone has RAM and battery, a shirt has size and fabric.
  • User preferences and feature flags.
  • Storing raw third-party payloads, such as a Razorpay webhook body, next to the extracted columns you actually query.

Trade-offs and gotchas

  • Planner statistics are weak for keys inside JSONB, so row estimates can be badly wrong. Promote hot keys to real columns or generated columns.
  • No per-key constraints or foreign keys. You lose type safety unless you add CHECK constraints.
  • Updates rewrite the whole value. Large documents (over about 2 KB) are TOASTed, so changing one key rewrites the compressed blob and creates bloat.
  • Using JSONB to avoid schema design turns into an untyped mess. A good rule: columns for what you filter, join and constrain on; JSONB for the long tail.

Code examples

Product attributes with a GIN index

CREATE TABLE products (
  id          BIGSERIAL PRIMARY KEY,
  category    TEXT    NOT NULL,
  price_paise INTEGER NOT NULL,
  attrs       JSONB   NOT NULL DEFAULT '{}'
);

CREATE INDEX products_attrs_gin ON products USING GIN (attrs jsonb_path_ops);

INSERT INTO products (category, price_paise, attrs) VALUES
 ('phone', 1499900, '{"brand": "Redmi", "ram_gb": 8, "5g": true}'),
 ('shirt',  79900,  '{"brand": "Allen Solly", "size": "M"}');

-- Containment query can use the GIN index
SELECT id, attrs->>'brand' AS brand
FROM products
WHERE attrs @> '{"5g": true}';

jsonb_path_ops makes @> lookups fast while staying smaller than the default GIN operator class.

Promoting a hot key to an indexed generated column

-- Generated columns (PG 12+) give real stats and B-tree indexes
ALTER TABLE products
  ADD COLUMN brand TEXT GENERATED ALWAYS AS (attrs->>'brand') STORED;

CREATE INDEX products_brand_idx ON products (brand);

-- Update one key without replacing the whole document in SQL
UPDATE products
SET attrs = jsonb_set(attrs, '{ram_gb}', '12')
WHERE id = 1;

A stored generated column keeps the value in sync automatically and gives the planner proper statistics for that key.

Key points

  • jsonb is parsed binary; json is stored verbatim text.
  • jsonb drops whitespace and key order and keeps only the last duplicate key.
  • GIN jsonb_ops supports ? and @>; jsonb_path_ops is smaller and supports @> and jsonpath.
  • Use B-tree expression or generated-column indexes for a single frequently filtered key.
  • Keep filtered, joined and constrained fields as real columns; use JSONB for the variable remainder.

Common follow-up questions

  • When would you choose MongoDB over PostgreSQL with JSONB?
  • How would you enforce that a JSONB column always contains a numeric price key?
  • Why can query plans on JSONB filters be inaccurate, and how do you fix that?
  • What is TOAST and how does it affect large JSONB updates?

Interview tips

  • Contrast json and jsonb concretely (parsing, key order, duplicates, indexing) instead of saying "jsonb is faster".
  • Mention the hybrid approach: real columns for core fields plus JSONB for variable ones. Interviewers look for judgment here.
  • Name the operator classes jsonb_ops and jsonb_path_ops if indexing comes up.

Concepts covered

JSONB, GIN Index, PostgreSQL, Semi-Structured Data, Containment Operator

More Database Design questions