[{"data":1,"prerenderedAt":6},["ShallowReactive",2],{"post-content-postgres-jsonb-gin-index-estimates":3},{"content":4,"lastModified":5},"\u003Ch2>One index, two very different results\u003C\u002Fh2>\n\n\u003Cp>A ticket came in two weeks ago about a reporting page that used to load in under a second and now took six or seven. The filter behind it was one key inside a jsonb column. I rebuilt the table from that ticket in a scratch database instead of guessing: 200,000 rows in a 36MB heap, 90% of the documents carrying \u003Ccode>{\"cat\":\"common\"}\u003C\u002Fcode>, the rest spread across a hundred rare values at 200 rows each.\u003C\u002Fp>\n\n\u003Cp>Without an index both queries were a plain sequential scan, 22 to 28ms, 4,546 shared buffers. So I built the obvious thing.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-sql\">CREATE INDEX events_data_gin ON events USING gin (data);\n-- 3,552 kB of index against a 36MB heap\n\nSELECT count(*) FROM events WHERE data @> '{\"cat\":\"rare42\"}';\n--  Bitmap Index Scan on events_data_gin\n--  Execution Time: 1.106 ms   (the seq scan took 23.9 ms)\n\nSELECT count(*) FROM events WHERE data @> '{\"cat\":\"common\"}';\n--  Seq Scan on events\n--  Execution Time: 39.690 ms\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>Same index, same column, same operator. One query got 22 times faster and the other kept the plan it already had. If you have ever added a GIN index and watched nothing improve, this is about where you stopped looking.\u003C\u002Fp>\n\n\u003Ch2>GIN answers containment, and very little else\u003C\u002Fh2>\n\n\u003Cp>That second plan is correct. When 180,000 of 200,000 rows match, reading the table once beats walking most of it through an index and then chasing matching heap pages. Postgres costed both plans and picked the cheaper one. Force it the other way with \u003Ccode>enable_seqscan = off\u003C\u002Fcode> and you get the bitmap plan in 39.4ms, against 39.7ms for the scan. There is nothing to win there.\u003C\u002Fp>\n\n\u003Cp>The problem is the shape people reach for first:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-sql\">SELECT count(*) FROM events WHERE data->>'cat' = 'rare42';\n--  Seq Scan on events\n--  Execution Time: 18.788 ms, with the GIN index still sitting there\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>\u003Ccode>->>\u003C\u002Fcode> pulls text out of the document and compares two strings. Nowhere in that expression is there a containment test, so no GIN operator class can serve it, and no amount of \u003Ccode>jsonb_path_ops\u003C\u002Fcode> tuning changes that. The index knows which documents contain a given value. This query never asks.\u003C\u002Fp>\n\n\u003Ch2>What the planner knows, and where it goes blind\u003C\u002Fh2>\n\n\u003Cp>Index choice is only half of it. The other half is row estimates, and that is where the two syntaxes split in a way I did not expect. Ask the catalog which selectivity function each operator uses:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-sql\">SELECT oprname, oprleft::regtype, oprrest\nFROM pg_operator\nWHERE oprname IN ('@>', '->>') AND oprleft::regtype = 'jsonb';\n\n oprname | oprleft |   oprrest\n---------+---------+--------------\n ->>     | jsonb   |\n @>      | jsonb   | matchingsel\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>\u003Ccode>->>\u003C\u002Fcode> has no restriction selectivity function at all. The planner falls back to \u003Ccode>DEFAULT_EQ_SEL\u003C\u002Fcode>, 0.005, so every comparison against an extracted key gets costed at half a percent of the table. On 200,000 rows that is exactly 1,000, and 1,000 is what I got for both of these:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-sql\">WHERE data->>'cat' = 'common'   -- estimated 1,000, actually 180,000\nWHERE data->>'cat' = 'rare42'   -- estimated 1,000, actually 200\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>One estimate is 180 times too small, the other five times too large, and they are the same number. On its own that costs you a bad access path. In a join it picks the join method, which is how a plan that stays flat on your test tenant turns into a nested loop against the biggest customer you have.\u003C\u002Fp>\n\n\u003Cp>\u003Ccode>@>\u003C\u002Fcode> gets \u003Ccode>matchingsel\u003C\u002Fcode>, and that one really does consult the histogram of the column. Same table, same data: 181,818 for \u003Ccode>common\u003C\u002Fcode> against 180,000 actual, 20 for \u003Ccode>rare42\u003C\u002Fcode> against 200. So containment is not blind here. Extraction is.\u003C\u002Fp>\n\n\u003Cfigure>\n  \u003Cimg src=\"https:\u002F\u002Fimages.pexels.com\u002Fphotos\u002F6333856\u002Fpexels-photo-6333856.jpeg?auto=compress&amp;cs=tinysrgb&amp;w=1200\" alt=\"Rows of wooden library card catalog drawers with small handwritten labels on the fronts\" loading=\"lazy\" width=\"1080\" height=\"720\">\n  \u003Cfigcaption>The planner reads the label on the drawer, never what is inside it.\u003C\u002Ffigcaption>\n\u003C\u002Ffigure>\n\n\u003Ch2>Fixes, in the order I would try them\u003C\u002Fh2>\n\n\u003Cp>If the filter is pure containment, rewrite it. \u003Ccode>data @> '{\"cat\":\"rare42\"}'\u003C\u002Fcode> keeps the GIN index usable and hands the planner an estimate it can work with. When the matched set turns out to be most of the table, the seq scan you get back is the right answer, and the fix lives in the query or the schema rather than in the index.\u003C\u002Fp>\n\n\u003Cp>Ranges and casts need a typed expression index, double brackets included. My numeric range filter was estimated at 66,667 rows when 1,200 matched, the one-third default for inequality. With the index in place the estimate moved to 1,310 and the query ran in 0.57ms instead of 30.6ms.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-sql\">CREATE INDEX events_amount_num ON events (((data->>'amount')::numeric));\n\n-- uses the index: same expression, same cast\nWHERE (data->>'amount')::numeric > 990\n\n-- misses it, and lies to you\nWHERE data->>'amount' > '99'\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>The second one is not a slower query, it is a wrong one. Text comparison sorts \u003Ccode>'100'\u003C\u002Fcode> below \u003Ccode>'99'\u003C\u002Fcode>, so it returned 1,400 rows where the numeric version returns 179,901. No error, no warning, just a different number on the dashboard. Any missing cast in your codebase fails this way.\u003C\u002Fp>\n\n\u003Cp>And if you want the estimates but not another index on a write-heavy table, extended statistics work on expressions since Postgres 14:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-sql\">CREATE STATISTICS events_cat_stats ON (data->>'cat') FROM events;\nANALYZE events;\n-- same query, no index involved: estimate went from 1,000 to 173\n-- (actual: 200)\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>I should have known about that one years ago. Two lines, nothing to maintain, and \u003Ccode>->>\u003C\u002Fcode> stops being invisible to the planner. The catch is that it only applies to predicates matching the expression exactly: statistics on \u003Ccode>(data->>'cat')\u003C\u002Fcode> do nothing for \u003Ccode>(data->>'cat')::int\u003C\u002Fcode>.\u003C\u002Fp>\n\n\u003Cp>These probes are the ones I keep re-typing, mostly because I can never remember the \u003Ccode>pg_operator\u003C\u002Fcode> query, so they sit in \u003Ca href=\"\u002Fsnippetark\u002F\" rel=\"noopener noreferrer\" target=\"_blank\">Snippet Ark\u003C\u002Fa> beside the rest of my EXPLAIN material. If you want the other half of the workflow, comparing what the plan predicted against what actually ran, my notes on \u003Ca href=\"\u002Fposts\u002Fpg-stat-statements-hidden-cost\u002F\">pg_stat_statements\u003C\u002Fa> go through it, and \u003Ca href=\"\u002Fposts\u002Fpostgres-not-using-my-index-what-i-check\u002F\">the checklist for an index Postgres refuses to use\u003C\u002Fa> covers the plain btree case.\u003C\u002Fp>\n\n\u003Cp>Most jsonb advice stops at \"add a GIN index\". The index was never the hard part. Matching the operator to the index, and knowing that one of the two syntaxes will never get a real row estimate, is what decides whether the query runs in one millisecond or forty.\u003C\u002Fp>\n","2026-11-23",1795678594073]