•5 min read

jsonb Query Slow? ->> Has No Index and No Statistics

One index, two very different results

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 {"cat":"common"}, the rest spread across a hundred rare values at 200 rows each.

Without an index both queries were a plain sequential scan, 22 to 28ms, 4,546 shared buffers. So I built the obvious thing.

CREATE INDEX events_data_gin ON events USING gin (data);
-- 3,552 kB of index against a 36MB heap

SELECT count(*) FROM events WHERE data @> '{"cat":"rare42"}';
--  Bitmap Index Scan on events_data_gin
--  Execution Time: 1.106 ms   (the seq scan took 23.9 ms)

SELECT count(*) FROM events WHERE data @> '{"cat":"common"}';
--  Seq Scan on events
--  Execution Time: 39.690 ms

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.

GIN answers containment, and very little else

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 enable_seqscan = off and you get the bitmap plan in 39.4ms, against 39.7ms for the scan. There is nothing to win there.

The problem is the shape people reach for first:

SELECT count(*) FROM events WHERE data->>'cat' = 'rare42';
--  Seq Scan on events
--  Execution Time: 18.788 ms, with the GIN index still sitting there

->> 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 jsonb_path_ops tuning changes that. The index knows which documents contain a given value. This query never asks.

What the planner knows, and where it goes blind

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:

SELECT oprname, oprleft::regtype, oprrest
FROM pg_operator
WHERE oprname IN ('@>', '->>') AND oprleft::regtype = 'jsonb';

 oprname | oprleft |   oprrest
---------+---------+--------------
 ->>     | jsonb   |
 @>      | jsonb   | matchingsel

->> has no restriction selectivity function at all. The planner falls back to DEFAULT_EQ_SEL, 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:

WHERE data->>'cat' = 'common'   -- estimated 1,000, actually 180,000
WHERE data->>'cat' = 'rare42'   -- estimated 1,000, actually 200

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.

@> gets matchingsel, and that one really does consult the histogram of the column. Same table, same data: 181,818 for common against 180,000 actual, 20 for rare42 against 200. So containment is not blind here. Extraction is.

Rows of wooden library card catalog drawers with small handwritten labels on the fronts
The planner reads the label on the drawer, never what is inside it.

Fixes, in the order I would try them

If the filter is pure containment, rewrite it. data @> '{"cat":"rare42"}' 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.

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.

CREATE INDEX events_amount_num ON events (((data->>'amount')::numeric));

-- uses the index: same expression, same cast
WHERE (data->>'amount')::numeric > 990

-- misses it, and lies to you
WHERE data->>'amount' > '99'

The second one is not a slower query, it is a wrong one. Text comparison sorts '100' below '99', 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.

And if you want the estimates but not another index on a write-heavy table, extended statistics work on expressions since Postgres 14:

CREATE STATISTICS events_cat_stats ON (data->>'cat') FROM events;
ANALYZE events;
-- same query, no index involved: estimate went from 1,000 to 173
-- (actual: 200)

I should have known about that one years ago. Two lines, nothing to maintain, and ->> stops being invisible to the planner. The catch is that it only applies to predicates matching the expression exactly: statistics on (data->>'cat') do nothing for (data->>'cat')::int.

These probes are the ones I keep re-typing, mostly because I can never remember the pg_operator query, so they sit in Snippet Ark 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 pg_stat_statements go through it, and the checklist for an index Postgres refuses to use covers the plain btree case.

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.