How to Choose Between JSONB and Relational Tables
Decide when to store structured data in JSONB columns versus normalized tables: weigh querying, indexing, constraints, and schema evolution.
On this page
Introduction
JSONB columns are attractive: store a blob of structured data, add a field without a migration, and read it back as JSON. They are also a way to avoid design decisions, and used for the wrong data they make queries slower and invariants unenforced. The right question is not whether to use JSONB but which data belongs in JSONB and which belongs in real columns.
This tutorial gives a decision procedure: identify the fields you query, join, aggregate, or constrain, keep those as columns, put genuinely dynamic per-row attributes in JSONB with the indexes they need, and validate the shape the database cannot enforce. The examples use PostgreSQL JSONB, whose indexing options shape the trade-offs.
Identify what you must query and constrain
Start from the operations. Every field you filter on, join to, sort by, aggregate across rows, or put a unique or foreign-key constraint on is a strong candidate for a real column. These operations on a column use an index and a constraint directly; on a JSONB path they may require a special index, cannot use a foreign key, and treat a missing key as a third state that constraints rarely handle.
Be concrete about cardinality and frequency. A field you filter on a million times a day, or that must be unique, belongs in a column. A field you store and read but never query across rows, such as a per-row configuration blob, fits JSONB. The decision is per field, not per table; a table can have core columns for the queryable data and a JSONB column for the variable rest.
-- queryable, constrained fields as columns; variable extras as JSONB
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL UNIQUE, -- filtered and constrained
price_cents integer NOT NULL, -- aggregated and financially important
category_id bigint NOT NULL REFERENCES categories (id),
attributes jsonb NOT NULL DEFAULT '{}' -- per-category variable fields
);
Keep dynamic data in JSONB
JSONB excels when rows have different sets of attributes and you rarely need to query them uniformly. Product attributes that differ by category, feature flags, or a webhook’s raw payload all fit: they vary per row, they are read whole or by a known key, and forcing them into columns would mean many sparse columns or a subtype table per variant.
Prefer jsonb to json in PostgreSQL. jsonb is stored in a decomposed form that supports indexing and is faster to query, at the cost of a little write overhead and lost key order and duplicate keys. json keeps the exact text, which matters only when the raw form must be preserved. For anything you will query, choose jsonb.
-- variable attributes, queried by containment
SELECT id, attributes
FROM products
WHERE attributes @> '{"color": "red", "size": "L"}';
Index the JSONB paths you query
A JSONB column without an index makes every query a sequential scan. A GIN index supports containment operators such as @> and ?, which match a document containing a key or a value. This is the right index when you query many shapes and want general containment. It is larger and slower to update than a b-tree, so weigh it against the write load.
For a hot query on a single known path, an expression index on that path is smaller and faster than a GIN index. An index on (attributes->>‘status’) supports equality and range on that path and costs far less than indexing the whole document. Combine both: a GIN index for exploratory queries and an expression index for the one path on the critical read path.
-- general containment queries
CREATE INDEX idx_products_attributes_gin ON products USING gin (attributes);
-- one hot path, smaller and faster
CREATE INDEX idx_products_attributes_status ON products ((attributes->>'status'));
Validate what the database cannot enforce
A JSONB column accepts any shape, so a missing required key or a wrong type is caught only when a reader trips over it. Add a check constraint to enforce invariants the database can express, such as a required key or a value in an allowed set. Move the rest to application validation at the boundary, and validate on write so invalid documents never enter the table.
Document which keys are required and which are optional, and version the shape if it changes incompatibly. A schema registry or a documented contract keeps readers and writers aligned. Do not rely on readers to defend against every missing key; a documented shape plus a check constraint for the hard invariants reduces the error handling to the genuinely optional cases.
ALTER TABLE products ADD CONSTRAINT attributes_valid_shape
CHECK (attributes ? 'color' AND attributes->>'color' <> '');
Test paths, indexes, and constraints
Test that a containment query returns the expected rows and that the GIN index is used by reading the plan. Test that an expression index supports the hot path query. Test that a document missing a required key is rejected by the check constraint. Test that reading a document with an optional key absent does not throw. These tests cover the query, the index, and the validation boundary.
psql -d app -c "EXPLAIN SELECT id FROM products WHERE attributes @> '{\"color\":\"red\"}';"
# assert the plan uses idx_products_attributes_gin
psql -d app -c "INSERT INTO products (sku, price_cents, category_id, attributes) VALUES ('x',1,1,'{}');"
# expect a check-constraint violation for the missing color key
Common pitfalls
Putting joined or aggregated fields in JSONB and fighting the planner, storing foreign-key relationships as JSON ids with no referential integrity, indexing every JSONB column even when it is never queried, using json instead of jsonb for queried data, and assuming JSONB removes the need for validation are the recurring mistakes. Columns for queried data, JSONB for variable data, targeted indexes, and a check constraint address them.
Conclusion
The JSONB-versus-columns question is answered per field. Keep fields you query, join, aggregate, or constrain as columns with indexes and constraints, store genuinely variable per-row data in JSONB, index the JSONB paths you query with the right index type, and validate the shape the database cannot. Self-check by asserting containment queries use the GIN index and that a missing required key is rejected. The result is flexibility without giving up the database’s ability to enforce and search.
Sources: PostgreSQL: JSON types, PostgreSQL: JSON functions and operators, PostgreSQL: GIN indexes for JSONB.
FAQ
- When is JSONB the wrong choice?
- When a field is joined on, has a foreign key, is aggregated across rows, or needs a unique constraint. Those operations are far more efficient on a real column with an index and a constraint than on a value buried in JSON.
- Does JSONB replace migrations?
- It reduces them for additive, per-row attributes, since adding a key needs no schema change. But you lose the database's type and constraint checks, so validation moves to the application or a check constraint, and readers must handle missing keys.
Report a problem with this articleOpens a pre-filled issue on GitHub.