Video in progress

The team proposes stuffing many fields into a `jsonb` column: "no need to change the schema". When do you agree and when do you push back?

For truly variable, rarely queried attributes (settings, external API responses, type-specific properties of a product) jsonb is good. But fields that are filtered on, joined on, need a constraint, or are updated often should be in regular columns.

📖 Answer

"No schema" actually means "the schema is in the code, hidden and unchecked". Three months later the same field lies around under the names "phone", "phoneNumber" and "tel".

The practical costs of jsonb:

  • No statistics. The planner doesn't know the selectivity for attrs->>'color' = 'red' and gets an approximate (often wrong) count. An expression index or CREATE STATISTICS on the expression (PG 14+) helps in part.
  • No constraints. NOT NULL, FK, type: all of it is in the application. You can add some with CHECK, but it's awkward.
  • Updates are expensive. Changing one field rewrites the whole document; if a big document is in TOAST, it's even more expensive. HOT can also be lost.
  • Size. The key names are repeated in every row.

When I agree:

  • A product catalog: each category has its own attributes (a phone has memory, clothing has size). The common fields in columns, the rest in jsonb + a GIN index.
  • External webhook payloads, for audit: "exactly as it arrived".
  • User settings, feature configurations.

My hybrid approach: every field used in filtering, sorting, reporting and JOINs is a column. If some jsonb field starts showing up often in queries, I "promote" it into a column (a generated column or a migration). On the Java side I map jsonb not to a Map but to a typed record (in Hibernate 6, @JdbcTypeCode(SqlTypes.JSON)), so that at least the schema exists in the code.