Expression Statistics (or when PostgreSQL guesses wrongly)
Recently, I was trying to make sense of some distribution data stored in a JSONB column. The query was a fairly simple SELECT + GROUP BY, but it was taking an uncomfortable amount of time, so it felt like a good place to figure out what Postgres was actually doing.
Here was our query:
SELECT
"userId",
COUNT(*) FILTER (WHERE engine = 'CLOB') AS clob_trades,
COUNT(*) FILTER (WHERE engine = 'AMM') AS amm_trades
FROM trades
WHERE metadata->>'platform' = 'relay'
AND engine IN ('CLOB', 'AMM')
GROUP BY "userId";
With an EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON), the query plan looked like this:

To explain the plan, Postgres estimated that around 195,000 records would pass the filter but got over 34 million records in reality. It also attempted an external sort, followed by a group aggregation (to satisfy the GROUP BY clause) that spilled to disk.
The where filter column/field had been left intentionally unindexed, as this wasn’t something we query regularly, and the cost of adding an index for such one-off query was not worth it. Hence, the goal shifted from purely making the query faster, to seeing what improving Postgres’s own estimates could bring, which led to expression statistics.
How PostgreSQL plans a query
A Postgres query goes through these stages:
Parse: Here, PG checks that your query is valid.
Analyze/Rewrite: Resolves tables, columns, types and other database objects. The rewrite also expands views (if used), etc.
Plan: Finds the cheapest way to get the results you asked for.
Execute: Runs the plan estimated to be the cheapest from the stage above and returns the results.
The planning stage is where PG decides how best to execute the query, considering factors like:
- the query itself: e.g is there an order by, limits?
- available indexes: are there indexes supporting the query’s filter, ordering or joins?
- available statistics: these are data that postgres has gathered about the distribution of the data we have. These include statistics like how many rows exist in total, how many unique rows exist, what are the most common values (MCVs), etc. These factors help the query planner give a “cost estimate” to each execution plan, and select a plan based on its relative cost - hence the postgres query planner is know as a Cost-based optimizer.
Cost in this case is an abstract unit that is tied to reading one sequential page from disk (seq_page_cost = 1.0). Other costs are expressed relative to this sequential access (e.g cpu_tuple_cost, cpu_operator cost).
For example, a sequential scan reads all pages belonging to a table one by one, which is cheap per page (but expensive if you’re only looking for a single row). Sequential scans also evaluate every row against the filters. A simplified cost of such a sequential scan looks like this:
(pages × seq_page_cost) + (rows × cpu_tuple_cost) + (rows × estimated per-row filter evaluation cost)
Estimating Matching Rows
The query planner we mentioned above can only work with estimates (working with actual values would require it to actually execute your queries which is expensive upfront and defeats the purpose of planning). There are two kinds of estimates here:
- Cardinality: This is an estimate of the total number of rows in a table. Since a query plan consists of multiple stages, cardinality is also the number of rows returned in each stage of the plan.
- Selectivity: This is a fraction of the number of rows expected to match your query’s filter (called the predicate). It is a number between 0 and 1. For example, a selectivity of 0.01 implies that 1% of rows are expected to match.
Combined, these two estimates give the planner an “estimated number of rows” that would be returned, which it then uses to decide for example, whether a sequential scan, or an index scan would be cheaper.
As an example, suppose we have 100 million rows and PG statistics indicates a selectivity of 0.2 for the predicate WHERE engine='CLOB';, the estimated rows would be:
Estimated Rows = Cardinality Estimate * Selectivity
-> 100,000,000 * 0.2 = 20,000,000.

This works when Postgres has statistics for the predicates you are filtering on, when it doesn’t, it falls back to hard coded defaults which sometimes (like in our original query), can be problematic.
Where Postgres guessed wrongly
Our query’s predicate is WHERE metadata->>'platform , essentially extracting a JSONB field. Postgres’ statistics generally do not provide the data distribution for such fields.
Since it has no idea of the data distribution on the inner platform field, it fellback to the 0.005 (0.5%) selectivity. We see that in the estimates below
SELECT reltuples::bigint
FROM pg_class
WHERE oid = 'public.trades'::regclass;
reltuples|
---------+
39020704|
The estimated matching rows become: [ 39,020,704 \times 0.005 \approx 195,104 ] This is almost exactly the 195,103 we saw in the initial estimate, as against the 34 million rows that actually matched.
To help it better understand this distribution, we need to help it create better statistics.
Enter expression statistics
The Postgres docs describes the CREATE STATISTICS command as a way to collect statistics for a single expression or virtual generated column, providing benefits similar to an expression index without the overhead of index maintenance. Expressions in this case include type casts (e.g., amount::numeric), functions (e.g., lower(username)), and operations like our JSONB extraction (metadata->>'platform').
The goal is to give the query planner enough insights into our data distribution, which helps its selectivity estimates, and in turn, help it chose a cheaper plan. For this, we create our expression statistics on the predicate expression like so:
CREATE STATISTICS trades_platform_stats
ON (metadata->>'platform')
FROM public.trades;
This is followed by a manual ANALYZE query that prompts postgres to analyze rows and collect statistics on the table immediately, as opposed to waiting for the routine automatic analysis.
ANALYZE public.trades;
We can also verify the newly collected statistics by running:
SELECT
statistics_name,
expr,
n_distinct,
null_frac,
most_common_vals,
most_common_freqs,
histogram_bounds
FROM pg_stats_ext_exprs
WHERE tablename = 'trades';
Revisiting the execution plan
Re-running explain on the same query with the improved statistics now look like this:
Here, we see multiple improvements over the initial query plan. For example, the planner now estimates ~34.4 million records to match - almost the same as the actual number that matched.
It still opted for the sequential scan (which makes sense, considering most of the records in the table matched our filter), but picked a different aggregation strategy. Without the statistics, Postgres sorted million of rows by userId before aggregation, but now, it used a hash aggregation that lets it accumulate counts in a small hash table, using the userId as the hash key. This almost halved the execution time and removed the large external sort (and the accompanying disk IO), keeping all of the aggregation work in memory, without needing to increase either the work_mem value, or adding a new index.
Here’s how our new plan looked:
| Metric | Before | After |
|---|---|---|
| Estimated matching rows | ~195K | ~34.4M |
| Actual matching rows | 34.4M | 34.4M |
| Estimated final groups | 1,321 | 1,281 |
| Actual final groups | 118 | 118 |
| Aggregation strategy | Sort + GroupAggregate | HashAggregate + small Sort |
| Temporary I/O | ~1.93 GiB read, ~1.93 GiB written | None |
| Observed execution time | 12.87s | 6.70s |
Where this is useful
Expression statistics are particularly helpful when we are working with:
- Filters on expressions: E.g., metadata-»‘platform’, date_trunc(‘day’, created_at), (payload-»‘amount’)::numeric, etc., where ordinary statistics may not sufficiently describe the data distribution.
- Write-heavy, large tables: In this case, indexes come with extra cost on inserts and updates, the cost of expression statistics comes during the analyze phase when postgres is sampling.
- Poorly-selective predicates: When most of the rows matches a filter, an index offers little benefit. In our case,
platform = 'relay'matches a large share of the table, hence, the planner might choose a sequential scan even with an expression index. However, expression statistics can still help Postgres estimate how much data it is likely to process.
There are some limitations. For example, they only help with compatible expressions (i.e., statistics on lower(email) will not translate to upper(email)), and statistics could become stale over time. Also, they do not offer new data access paths (like indexes).