Data

JSONB or typed classes: what the PostgreSQL planner sees

Redbase Blog Rinat Kozin
Data

Because PostgreSQL keeps no statistics for keys inside a jsonb document, Pachot's example predicted one row where 12,491 matched. The article reruns that query over typed C# classes and sets the plans, row estimates and timings side by side.

Key points

  • PostgreSQL applies 0.5% default selectivity to each JSONB expression, predicting one row where 12,491 matched.
  • A compound expression index answered in 11.1 ms; three separate expression indexes took 25.9 ms.
  • Extended statistics alone left the JSONB query at 26.5 ms; they cover columns, not document keys.
  • redb stores each field as a values-table row and reuses one system index for every int field.
  • Joining three field rows per object still skews estimates: 18,000 predicted for Value1 = 0 against 49,969 actual.
  • The typed nested-class query ran in 50.5 ms, versus 11.1 ms for JSONB with a hand-made index.

Why it matters

If you filter on keys inside a jsonb column, PostgreSQL is guessing: ANALYZE sees the document, not value_1, so every key condition falls back to default selectivity. The fix that pays is one compound expression index over exactly the expressions your hot query uses; separate expression indexes do worse on a combined predicate, and extended statistics do not rescue you.

The redb comparison concedes something useful: typing removes the per-query index declaration and adds compiler-checked fields and foreign keys, but it shifts the estimation problem onto joins over value rows instead of erasing it. This is a vendor benchmark on a development branch and a single machine, so read the millisecond gaps as relative, not absolute.

Real-world use

  • Reporting and dashboard queries that filter a measurements table on several flag columns and count by lab
  • Applications whose filter queries change with the code and cannot afford a new expression index for each
  • A parent/child model where the lab owns its measurements, so grouping by parent is the first step

This summary was generated by the agent from the original post on Redbase Blog. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message