How to Optimize JSONB Aggregation Queries
Aggregate over JSONB efficiently: extract and cast in the right place, build expression indexes, and avoid per-row expansion that kills plans.
On this page
Introduction
JSONB is flexible to write and can be slow to aggregate. Summing a value buried in a JSON document means extracting and casting a path per row, and if the query also expands arrays or joins on extracted keys, the work multiplies. The difference between a JSONB aggregation that runs in milliseconds and one that scans for seconds is usually where the extraction happens and whether an index covers it.
This tutorial covers extracting and casting JSONB paths once, indexing the extracted expression, avoiding the row explosion that array expansion causes, and testing both correctness and the plan. The examples use PostgreSQL JSONB, whose array expansion and expression-index behavior define the traps.
Extract and cast the path once
Each access to a JSONB path with -> or ->> returns text or json, and each cast to a number or a timestamp runs per row. If a query touches the same path in the WHERE clause, the GROUP BY, and the SELECT, it may parse and cast the value three times per row. Extract the path into a typed value once in a subquery or a lateral, name it, and aggregate on that name so the work happens once.
A lateral join or a CTE is the clean way to do this. The lateral computes the typed value for each base row and the outer query aggregates over it, while the planner can push a filter down. This turns repeated extraction into a single computation and makes the query readable, so the intent is visible rather than buried in a chain of operators.
-- extract and cast once, then aggregate on the typed value
SELECT region,
sum((amount)::numeric) AS total
FROM (
SELECT payload->>'region' AS region,
payload->>'amount' AS amount
FROM orders
WHERE payload ? 'amount'
) t
GROUP BY region;
Index the extracted expression
An expression index on a JSONB path lets the planner seek instead of scanning. If the query filters payload->>‘region’ = $1, an index on (payload->>‘region’) turns the scan into a seek and makes the aggregation read only the matching rows. Without it, the query scans every row, extracts and casts each, and only then filters, which is where the seconds go.
Cast inside the index expression when you filter or group on a number. An index on ((payload->>‘amount’)::numeric) supports range filters on the amount, whereas an index on the text path does not. Match the expression in the index to the expression in the query exactly; a planner will not use an index on a text path for a query that casts to numeric, because the expressions differ.
-- index the exact expressions the query uses
CREATE INDEX idx_orders_region ON orders ((payload->>'region'));
CREATE INDEX idx_orders_amount ON orders (((payload->>'amount')::numeric));
-- now a range filter can seek
SELECT count(*) FROM orders WHERE (payload->>'amount')::numeric > 1000;
Avoid the row explosion from array expansion
jsonb_array_elements expands a JSON array into one row per element, multiplying the row count. If a query expands an array for a thousand rows each holding a ten-element array, it produces ten thousand rows before it aggregates, and any index on the base table no longer applies to the expanded rows. This is the JSONB equivalent of a many-to-many join without deduplication.
Filter and limit before you expand. Apply the indexed filters on the base table first so only the needed rows reach the expansion, then expand. If the aggregate is a sum over array elements, consider whether the array should instead be a child table with one row per element, where a normal index and a normal aggregate apply. Keep expansion as the last step, over the smallest possible set of rows.
-- filter the base rows first, expand last
SELECT o.id, elem->>'sku' AS sku, (elem->>'qty')::int AS qty
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.payload->'items') AS elem
WHERE o.payload->>'region' = $1 -- indexed filter narrows the expansion
AND o.created_at >= $2;
Prefer columns for hot aggregates
If a JSONB value is aggregated on every dashboard query, the durable fix is a real column. A typed column has an index and a constraint, and the aggregation reads the value without extraction or casting. Keep the JSONB for the genuinely variable attributes and promote the fields that are always present and always queried to columns, populated at write time from the JSON if needed.
A generated column can bridge the two: derive a typed column from the JSONB path with a generated expression, then index it. The value stays in step with the JSON automatically, and queries use a plain column, avoiding the extraction in every query. This is the cleanest way to keep the write-side flexibility of JSONB while giving the read side a typed, indexed column.
ALTER TABLE orders
ADD COLUMN amount_cents bigint
GENERATED ALWAYS AS (((payload->>'amount')::numeric * 100)::bigint) STORED;
CREATE INDEX idx_orders_amount_cents ON orders (amount_cents);
SELECT sum(amount_cents) FROM orders WHERE amount_cents > 100000;
Test correctness and the plan
Test that the aggregate equals a hand-computed value over a small dataset with known rows, including a row whose JSON lacks the key, so the null handling is pinned. Test that the expression index is used by reading the plan for the filtered aggregate. Test that the array expansion produces one row per element and none for an empty array. These tests cover the value, the plan, and the expansion edge case.
psql -d app -c "EXPLAIN (ANALYZE) SELECT sum((payload->>'amount')::numeric) FROM orders WHERE (payload->>'amount')::numeric > 1000;"
# assert the plan uses idx_orders_amount, not a Seq Scan
Common pitfalls
Extracting and casting the same path multiple times per row, filtering on a JSONB path with no expression index, indexing the text path but filtering on a cast numeric, expanding arrays before applying indexed filters, and keeping a hot aggregated number only in JSONB are the recurring mistakes. Extract once, index the exact expression, filter before expanding, and promote hot fields to columns address them.
Conclusion
JSONB aggregation is fast when the extraction happens once and an index covers it. Extract and cast the path in one step, index the exact expression the query uses, filter before expanding arrays, and promote hot aggregated fields to typed or generated columns. Self-check by asserting the aggregate matches a hand-computed value and that the plan uses the expression index. Then flexible storage does not cost query speed on the fields that matter.
Sources: PostgreSQL: JSON functions and operators, PostgreSQL: Expression indexes, PostgreSQL: Aggregate functions.
FAQ
- Why is casting JSONB numbers slow?
- Every cast from text to a number runs per row and is not covered by an index unless you index the expression. On a large table this means parsing and casting millions of values. Extract the path once and index the typed expression so the work happens in the index, not per row.
- When should I keep a number as JSONB vs a column?
- If you aggregate or range-filter it, put it in a typed column. JSONB numbers are stored as a numeric-like type that still needs extraction and casting for arithmetic, and no constraint protects them. Move hot numeric fields to columns.
Report a problem with this articleOpens a pre-filled issue on GitHub.