skip to content

In a PostgreSQL survey-builder, reports filter and sort on a few jsonb answer keys; what signs say a key should become a real column, and how do you promote it?

level: seniorimportance: should knowfreq 55%

answer

  1. no per-key planner statistics
  2. whole value rewritten per update
  3. types, NOT NULL, foreign keys
  4. expression index or statistics first
  5. 18: generated columns default VIRTUAL

basics

~20 s

Promote a key that nearly every row has and that queries filter, join, sort or constrain on: the planner keeps no per-key statistics, jsonb enforces no type, NOT NULL or foreign key, and every change rewrites the whole document.

solid answer

~50 s

Signals: the key is in nearly every document with one type; it appears in WHERE, JOIN, ORDER BY or GROUP BY; it needs NOT NULL, a foreign key or a real type; or it changes often on its own. `ANALYZE` keeps statistics on the whole `answers` value, not per key, so `answers->>'plan' = 'pro'` gets a built-in guess and plans go wrong; an expression index or `CREATE STATISTICS` on the expression gives it something to measure. Every update writes a new row version with the whole document, and a large out-of-line document is stored again in full. To promote, add a nullable typed column, backfill in batches, write both until readers switch, add constraints, then drop the key. Or add `GENERATED ALWAYS AS ((answers->>'nps')::int) STORED`: in PostgreSQL 18 a generated column defaults to VIRTUAL, which cannot be indexed, and adding a STORED one rewrites the table.

code

sql · 8 lines
sql
-- Give the planner statistics for the key without a migration
CREATE STATISTICS form_responses_plan_stats ON (answers->>'plan') FROM form_responses;
ANALYZE form_responses;

-- Promote nps through a stored generated column (rewrites the table)
ALTER TABLE form_responses
  ADD COLUMN nps int GENERATED ALWAYS AS ((answers->>'nps')::int) STORED;
CREATE INDEX form_responses_nps_idx ON form_responses (nps);

go deeper

for a junior

Recall that values inside jsonb have no column type or constraints of their own, and that keys queried in most reports are candidates for real columns.

for a middle

Explain why the planner misestimates filters on jsonb keys, how expression indexes and CREATE STATISTICS give it statistics, and that every update rewrites the whole document.

for a senior

Lay out a safe promotion: nullable column, batched backfill, dual writes, constraints added on a live table, and 18's VIRTUAL default and table rewrite when choosing a generated column.

for a principal

Set the rule for what lives in the document versus columns, with shared, queried and constrained keys promoted and per-customer variability kept in jsonb, plus a review step that catches drift.

## The question behind the question A survey-builder stores each submission's answers in a `jsonb` column because every customer designs different forms. Over time a few keys stop being customer-specific: every form gets a `plan`, an `nps` score and a respondent `email`, and every report filters, groups and sorts on them. The engine-neutral trade-off between documents and typed columns is a schema-design topic; this answer is about the PostgreSQL mechanics that show a key has outgrown the document. ## Signals that a key should be a column - **It is in nearly every row and has one type.** Its presence is no longer optional. - **Queries filter, join, sort or group on it.** `answers->>'plan'` appears in the `WHERE`, `JOIN`, `ORDER BY` or `GROUP BY` of most report queries. - **The planner misestimates it.** `ANALYZE` stores statistics for the `answers` column as a whole (most common whole documents and a histogram of whole documents), not for keys inside it. For `answers->>'plan' = 'pro'` it has no statistics, so on a large table it falls back to a built-in guess of 1 row in 200, whether `pro` is 2% or 90% of the rows. `@>` is estimated by testing the operator against the sampled whole-document statistics, with a 1% default when those are too thin. Wrong row counts lead to wrong join orders and scan choices. - **It needs integrity.** A key inside `jsonb` cannot carry `NOT NULL`, a foreign key or a declared data type; uniqueness and checks work only through expressions, such as a unique expression index or `CHECK (jsonb_typeof(answers->'nps') = 'number')`. - **It changes on its own.** Every update of any key writes a new row version containing the whole document, and a document large enough to be stored out of line (TOAST) is compressed and stored again in full. A frequently updated counter inside a large document multiplies write and vacuum work. - **Its name is repeated in every row.** Key names are stored inside each document, while a column name is stored once in the catalog. ## Cheaper fixes before a migration 1. **Expression index.** A B-tree index on `((answers->>'plan'))` serves equality and sorting on that exact expression, and `ANALYZE` gathers statistics for indexed expressions, which fixes the estimate as a side effect. 2. **Statistics object.** `CREATE STATISTICS ... ON (answers->>'plan') FROM form_responses` collects statistics for the expression without the cost of maintaining an index. 3. **Containment with a GIN index** for flexible multi-key filters on customer-defined fields that are not worth promoting. ## Promoting a key 1. **Add a typed, nullable column**; `ALTER TABLE ... ADD COLUMN plan text` with no default changes only metadata. 2. **Backfill in batches**, for example `UPDATE ... SET plan = answers->>'plan' WHERE id BETWEEN ...`, committing between batches so locks stay short and vacuum keeps up. 3. **Write both** from the application (or a trigger) until every reader uses the column. 4. **Add constraints** using the techniques for validating constraints on a live table, then remove the key from the documents. A **generated column** is the shortcut when the document stays the source of truth: `ADD COLUMN nps int GENERATED ALWAYS AS ((answers->>'nps')::int) STORED`. Two PostgreSQL 18 details matter: - Without `STORED`, a generated column is now **VIRTUAL** by default: computed when read, and it cannot itself be indexed (`indexes on virtual generated columns are not supported`), so you would index the expression instead or declare the column `STORED`. - Adding a `STORED` generated column rewrites the whole table and its indexes, a planned operation on a busy table, and a single bad value such as `"nps": "ten"` makes the rewrite fail with a cast error. ## What stays in jsonb The long tail stays in the document: per-customer custom fields, rarely queried answers and display-only metadata. A healthy design usually ends with a handful of typed columns plus one `jsonb` column for genuinely variable data, rather than all columns or all document.

  • How do you confirm that misestimation, rather than a missing index, is what makes a jsonb filter slow?
    Run `EXPLAIN (ANALYZE)` and compare the estimated and actual row counts on the node that applies the filter. An estimate near 0.5% of the table against a much larger actual count points at missing statistics. Create an expression statistics object or expression index, run `ANALYZE`, and check that the estimate moves before changing anything else.
  • A field matters to only one customer's forms but that customer filters on it heavily. Do you promote it to a column?
    Usually not: a column used by one tenant is NULL for everyone else and turns each customer request into a migration. Keep it in the document and serve the filter with containment over a GIN-indexed column, or with a partial expression index limited to that customer's forms if it is hot. Promote what is shared across tenants.

  • ANALYZE collects statistics for every key inside a jsonb column
  • Updating one key in a large jsonb document writes only that key
  • In PostgreSQL 18 a plain GENERATED ALWAYS AS column is stored and indexable
  • A key inside jsonb can carry a foreign key to another table
  • Adding a STORED generated column is a metadata-only change

Assumes PostgreSQL 18, where a generated column without STORED is VIRTUAL by default and cannot be indexed.