Sub topic 11
When to Use JSON Columns and When to Normalize
This chapter helps you decide, for a given piece of data, whether it belongs in a jsonb column or in ordinary relational columns and tables. It assumes you have read the earlier chapters on the access operators, jsonb_array_elements, jsonb_set, GIN and expression indexes, and CHECK constraints. It uses the orders table from the start of the tutorial.
The short answer is that JSON is a good fit for data whose shape varies or is rarely queried by field. Relational columns are a better fit for data that is stable, constrained, joined, or updated often. Most real schemas use both.
What a JSON column costs
A jsonb value is opaque to much of the database machinery. These costs are the reason to normalize.
- No foreign keys. A SKU inside
details -> 'items'cannot reference aproductstable. Nothing stops an order from naming a SKU that does not exist. - Weak typing.
qtycan be a number in one row and the string"2"in the next. Casts such as(i ->> 'qty')::intfail at query time instead of at insert time, unless you add CHECK constraints. - No per-key statistics. The planner keeps statistics for columns, not for keys inside a document. For a predicate like
details @> '{"status": "paid"}'it falls back to a generic selectivity estimate, which can produce poor plans. An expression index such as((details ->> 'status'))does get statistics afterANALYZE. - Whole-value updates.
jsonb_setreturns a new value, and PostgreSQL writes a new row version containing it. Changing one key in a 200 kB document rewrites all 200 kB. Large values are stored out of line (TOAST) and compressed, so reading one key also means fetching and decompressing the whole value. - Repeated keys. Each document stores its own key names. A million rows with a
"shipping"key store that word a million times. - Verbose queries. Aggregates and joins over nested arrays need
jsonb_array_elementsand casts, where normalized data needs a plain join.
What a JSON column gives you
- Flexible shape. Different rows can carry different keys without
ALTER TABLE. - Atomic documents. You read and write a whole aggregate, such as an order with its line items, in one row with no joins.
- Fast schema changes. Adding an optional attribute needs no migration.
- Pass-through storage. If your application stores a payload and returns it unchanged, such as a webhook body or user preferences, parsing it into columns adds work and no benefit.
Deciding per field
Make the decision for each part of the data, not once for the whole table.
The table below applies the same rules to the orders example.
| Data | Placement | Reason |
|---|---|---|
| `customer` | Column (later a `customers` table) | Joined, identifies a real entity |
| `status` | Column or generated column | Filtered in most queries, small fixed set of values |
| `total` | `numeric` column | Aggregated and summed |
| `items` | `order_items` table | Joined to products, aggregated by SKU, needs a foreign key |
| `shipping` | Either | Read as a whole and rarely filtered, so JSON is acceptable |
| Gateway payload, client metadata | `jsonb` | Varying shape, stored and returned as is |
Pattern: a hybrid table
Keep identity, keys, and frequently queried fields as columns. Put the variable remainder in one jsonb column.
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
price numeric(10,2) NOT NULL CHECK (price >= 0),
attrs jsonb NOT NULL DEFAULT '{}'::jsonb,
CONSTRAINT attrs_is_object CHECK (jsonb_typeof(attrs) = 'object')
);
INSERT INTO products (name, price, attrs) VALUES
('Desk lamp', 29.90, '{"color": "black", "wattage": 12}'),
('T-shirt', 15.00, '{"size": "M", "material": "cotton"}');
CREATE INDEX products_attrs_gin ON products USING gin (attrs jsonb_path_ops);The lamp and the T-shirt have different attributes, so a column per attribute would be mostly NULL. The name and price are used everywhere, so they are real columns with real constraints. The GIN index covers containment searches such as attrs @> '{"color": "black"}'.
Pattern: promote a hot key with a generated column
If a key starts to dominate your queries, you do not have to rewrite the table. A stored generated column copies the value out of the document and keeps it in sync automatically (PostgreSQL 12 or later).
ALTER TABLE orders
ADD COLUMN status text GENERATED ALWAYS AS (details ->> 'status') STORED;
CREATE INDEX orders_status_col_idx ON orders (status);
SELECT id, customer FROM orders WHERE status = 'paid';The column has its own statistics and a plain B-tree index. Application code still writes only details. The cost is extra storage for the copy and a table rewrite when you add the column. Compare this with the expression index from the indexing chapter. An expression index adds no column and no storage for a copy. A generated column can also be selected, joined, and used in a foreign-key or CHECK constraint.
Pattern: migrate a nested array into a table
The items array is the clearest candidate for normalizing. Each item has a SKU that should reference a product, and you want to sum quantities by SKU. Create the child table, then fill it from the documents with jsonb_array_elements.
CREATE TABLE order_items (
order_id bigint NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
sku text NOT NULL,
qty integer NOT NULL CHECK (qty > 0),
PRIMARY KEY (order_id, sku)
);
INSERT INTO order_items (order_id, sku, qty)
SELECT o.id, i ->> 'sku', (i ->> 'qty')::int
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.details -> 'items') AS i;
UPDATE orders SET details = details - 'items';The primary key on (order_id, sku) makes the migration fail if an order repeats a SKU, which tells you the old data had a problem. Run the three statements in one transaction so a failure leaves the data untouched. Adding a foreign key from order_items.sku to a products table would be the next step.
Reports then become ordinary SQL:
SELECT sku, sum(qty) AS units
FROM order_items
GROUP BY sku
ORDER BY units DESC;The JSON-only version of the same report needs the lateral expansion and casts, and it cannot use an index on sku:
SELECT i ->> 'sku' AS sku, sum((i ->> 'qty')::int) AS units
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.details -> 'items') AS i
GROUP BY 1
ORDER BY units DESC;Signals that you should normalize
Move a key or array out of JSON when you see one or more of these:
- The same key appears in the
WHERE,ORDER BY, orGROUP BYof most queries. - You need referential integrity, uniqueness across rows, or a
NOT NULLguarantee on a field. - The planner chooses bad plans for JSON predicates, and
EXPLAINshows row estimates far from reality. - Most updates touch one small key in a large document, and write volume or table bloat is a problem.
- Several teams or services read the data and need a documented, typed schema.
- You find yourself writing more CHECK constraints to recreate a table definition.
Signals that JSON is the right choice
- The set of keys is open-ended or differs by record type, as with product attributes, form answers, or feature flags.
- The data arrives from an external system whose format you do not control and you want to keep the original.
- You read and write the value as a unit and rarely look inside it.
- The structure is deeply nested and mapping it to tables would produce many small tables that are always joined back together.
Failure modes to watch for
- The catch-all column. A single
data jsonbcolumn holding everything gives up types, constraints, and statistics for no gain. Use at least a real primary key, timestamps, and the fields you filter on. - Unbounded growth. Documents that grow without limit, such as an event list appended to forever, make every update rewrite a larger value. Use a child table with one row per event.
- Indexing everything. A GIN index on a write-heavy column slows inserts and updates. Index the queries you run, and verify with
EXPLAINthat the planner uses the index. - Silent type drift. Without constraints, one writer sends
"total": "10"and another sends"total": 10. Cast failures then appear in reports weeks later. Add CHECK constraints for keys you depend on, for exampleCHECK (jsonb_typeof(details -> 'total') = 'number'). - JSON null versus SQL NULL.
details ->> 'tracking'returns SQLNULLboth when the key is missing and when its value is JSONnull. If the difference matters, test withdetails ? 'tracking'or comparedetails -> 'tracking'to'null'::jsonb.
A working rule
Start with columns for anything you can name today and that has meaning to your queries. Add a jsonb column for the parts you cannot name yet or that genuinely vary. When a JSON key becomes hot, promote it with a generated column or a migration like the one above. Moving data from JSON into columns is a routine, low-risk migration. Moving it the other way is rarely needed, so a hybrid design leaves you room to change.
Exercise
The orders.details documents contain "status", and 90% of your queries filter on it with equality. Name two ways to make those queries use a B-tree index without changing application writes, and say what each one costs.
Show answer
First, an expression index on ((details ->> 'status')). It costs only index storage and write overhead, and queries must use the same expression details ->> 'status' = .... Second, a stored generated column status text GENERATED ALWAYS AS (details ->> 'status') STORED with a normal index on it. It costs extra table storage and a table rewrite when added, but queries can use the plain status column, which can also appear in joins and constraints.
Exercise
A table stores each customer's activity log as a jsonb array in one column, and a new entry is appended on every click. Updates are getting slower as the arrays grow. Why does this happen, and what design fixes it?
Show answer
Appending one entry with || or jsonb_set produces a new jsonb value, so PostgreSQL writes a new row version containing the entire array. Large values are also stored out of line and compressed, so each update copies more data as the array grows. The fix is an activity table with one row per event (customer id, timestamp, and a small jsonb payload if the event details vary). Each click then becomes a small INSERT.