Fixing bad PostgreSQL query plans with extended statistics

When correlated columns make the PostgreSQL planner underestimate rows, extended statistics and higher per-column targets can correct the plan. This page explains how to choose, create and verify them.

On this page

Why PostgreSQL picks bad query plans when columns are correlated

Extended statistics fix row estimates when columns depend on each other. A typical case is a team whose report filters on city and postal_code in a customer table. The query runs slowly because the planner estimates a few dozen matching rows, the actual count is tens of thousands, and it picks a nested loop join that repeats work far more often than a hash join would. The planner is not broken. By default it assumes that the values in each column are independent of the values in every other column, so it multiplies the selectivity of each WHERE condition as if they had nothing to do with each other. When the columns are correlated, that product understates the real number of matching rows, often by a large factor.

The symptom to look for is a large gap between estimated and actual rows on a node in EXPLAIN ANALYZE output, especially on a scan or join that feeds a join above it. Before changing anything, confirm that the gap comes from the filter conditions and not from stale statistics, which a manual ANALYZE on the table will show. The fix is worth trying before a query rewrite or a new index when the predicates are on columns that are logically linked, such as a country and its currency code, a status and a closed date, or a product line and its category. In those cases a rewrite may only hide the estimate problem, and an index may be used or ignored depending on the same wrong estimate.

Which extended statistics kind fits which correlation problem

This table compares the dependencies, ndistinct and MCV statistics kinds, plus per-column statistics targets, against the planner symptom each one addresses. Read each row as a question: which misestimate are you seeing, and which kind of statistic answers it. The main takeaway is that every kind adds some planning and ANALYZE cost, so create only the objects that match a misestimate you have confirmed in EXPLAIN.

OptionSymptom it addressesApplies toTrade-off to weigh
Dependencies (functional dependencies)Planner multiplies selectivities of correlated equality filters as if independent, so row estimates come out too lowEquality conditions on correlated columns in WHERE clausesExtra ANALYZE work and a small planning cost; it does not help grouping or joins on those columns
NdistinctEstimated group count is far from the real number of distinct combinations, which skews GROUP BY, DISTINCT and some join sizingGrouping and distinct counts across a set of columnsExtra ANALYZE work and stored catalog data; it does not change single-column filter estimates
MCV (most common values) listFrequent value combinations across columns are misestimated, including non-uniform and skewed combinations that dependencies cannot modelEquality and range-style filters on combinations of columns, with common valuesLargest of the three in stored data and ANALYZE time, and it only covers the values sampled as common
Expression statisticsA filter on an expression, such as a function of a column, gets no useful estimate from column statistics aloneExpressions in WHERE, grouping or join conditionsEach expression adds a statistics object to maintain; confirm the expression matches the query exactly
Per-column statistics targetSingle-column estimates are coarse for a skewed or large column, so the planner picks a poor join order or scanOne column at a time, raising the sample detail used by ANALYZEHigher targets increase ANALYZE time and catalog size for that column; raise it only after the plan shows the gap
Choosing the kind by query shapeFilters on correlated columns versus grouping over the same columns need different kindsCheck the query: WHERE equality points to dependencies or MCV, GROUP BY points to ndistinctCreate the kind that matches the misestimated node, then confirm the effect with EXPLAIN ANALYZE after running ANALYZE

Create extended statistics and refresh them with ANALYZE

This sequence moves a misestimated query from diagnosis to a verified fix: it records the planner's bad estimate, creates a statistics object on the correlated columns, refreshes the table statistics, and confirms the new plan with evidence kept for review.

  1. Identify the misestimated query and table

    The DBA or database engineer starts from a query that is slow or unstable and has a plan node where the estimated row count is far from the actual count. Candidate queries usually come from pg_stat_statements or the slow query log, filtered to the table and the WHERE clause that combines the correlated columns. Record the query text, the table name, the column names and the predicate values that trigger the bad plan. The step is done when one query and its predicate are written down and can be rerun against the same data.

  2. Capture the baseline plan with EXPLAIN ANALYZE

    Run EXPLAIN (ANALYZE, BUFFERS) on the query in a session that matches production settings, and save the full output to a file that carries the date, the PostgreSQL version and the database name. Compare the estimated rows with the actual rows on each scan and join node, and note where the gap is largest, since the planner's choice of join method and scan type depends on those estimates. Run it more than once if timing varies, and keep the first output unchanged as the baseline. The step is done when the saved file shows the estimate and actual row counts for the problem node.

  3. Create the extended statistics object

    Using a role with ownership of the table, run CREATE STATISTICS with the correlated columns, selecting the kinds that match the problem: dependencies for functional dependency between columns, ndistinct for distinct-value counts across a column group, and mcv for most common value combinations. Give the object a name that describes the columns, for example a schema-qualified name tied to the table. Run this change through your normal change process, since it is a DDL statement that takes a lock on the table's catalog entries. The step is done when the command returns CREATE STATISTICS without error.

  4. Run ANALYZE on the table

    Extended statistics are not populated when the object is created, so run ANALYZE on the table, either as a manual command in a maintenance window or by waiting for autovacuum to process it. For a large table, confirm the sampling and autovacuum settings you are relying on, because the sample size determines how much the statistics reflect the data. Record the time and the PostgreSQL version of the run in your change log. The step is done when ANALYZE completes and the table's last analyze time is updated.

  5. Inspect pg_stats_ext and pg_stats_ext_exprs

    Query the pg_stats_ext view filtered to the table and the new object's name to confirm that the row exists and that the kinds you requested are populated, such as the dependency degrees, distinct counts or the most common value list. If the query uses expressions, check pg_stats_ext_exprs as well, since expression statistics are stored there. An empty result means the object has not been analyzed yet, so return to the previous step. The step is done when the view shows populated statistics for the columns you targeted.

  6. Recheck the plan and save the evidence

    Rerun EXPLAIN (ANALYZE, BUFFERS) with the same query and predicate values used for the baseline, and compare the estimated and actual rows on the problem node with the saved output. Check that the join method or scan type changed in the expected direction and that execution time and buffer use improved, without slowing other query shapes that depend on the same table. Store both EXPLAIN outputs, the CREATE STATISTICS command and the pg_stats_ext query results together in the change record. The step is done when the new plan shows a much closer estimate and the evidence file is filed with the change.

  7. Schedule refresh when data distribution changes

    Extended statistics describe the data as it was at the last ANALYZE, so they go stale when the distribution of the correlated columns shifts, for example after a bulk load, a new customer segment or a change in how a status column is used. Add the table to a review list that repeats the plan check after large data changes, and confirm that autovacuum analyzes the table often enough for your workload. Re-run the EXPLAIN comparison when query times regress. The step is done when the table has a named owner and a documented trigger for re-checking the plan.

Raising per-column statistics targets for skewed columns

PostgreSQL builds per-column statistics from a sample of rows during ANALYZE. For a column with many distinct values and a few values that appear far more often than the rest, the default sample can miss those frequent values, so the planner estimates their row counts from a flat average. The result is often a wrong row estimate for filters on the hot values, which then drives the wrong scan type. The per-column setting for this is ALTER TABLE ... ALTER COLUMN ... SET STATISTICS, which overrides the cluster-wide default_statistics_target for that one column. A higher value makes ANALYZE sample more rows and keep a longer most-common-values list for that column.

  • Confirm the symptom first: Compare estimated and actual rows on the filter node in EXPLAIN ANALYZE before changing anything.
  • Target one column: Apply the setting to the skewed column only, not to every column in the table.
  • Re-run ANALYZE: The new target takes effect at the next ANALYZE on the table, so run it manually and check the plan again.
  • Watch the most-common-values list: Check pg_stats after ANALYZE to see whether the frequent values now appear.
  • Pick the value from the documentation: Use the range described in the PostgreSQL planner statistics documentation as a starting point and confirm it against your data.

Check that the estimate for the hot value moves closer to the actual row count on the same query before keeping the change.

What can go wrong after changing statistics

Extended statistics and higher statistics targets change what the planner believes about your data, so every change can help one query and hurt another. The cards below cover the failure modes teams meet most often and the check that exposes each one.

Statistics go stale

Extended statistics are a snapshot taken when ANALYZE runs. After a bulk load, a change in the mix of values, or a new correlation between columns, the object still describes the old data. Check the last analyze time in pg_stat_user_tables and compare estimated rows with actual rows in EXPLAIN ANALYZE for the affected query. If the gap returns, the fix is a scheduled ANALYZE on that table, not a larger statistics target.

Plans that regress elsewhere

A dependency or MCV statistic changes estimates for every query that filters on the same column combination, not only the one you were tuning. A better estimate can flip a join from a hash join to a nested loop that performs badly on another path. Capture plans for your top queries from pg_stat_statements before and after the change, and rerun the same set in a staging copy.

ANALYZE load on large tables

Raising a column's statistics target makes ANALYZE read and summarize more sample rows, and it runs for each affected column. On a very large table, this can add I/O during a busy window and lengthen autovacuum runs that touch the same table. Measure how long ANALYZE takes on the table before and after the change, and schedule the larger targets in a quiet window if the duration matters to you.

Statistics on the wrong column set

Extended statistics only help when the column list matches the predicates the planner sees. A statistic on (city, postal_code) does nothing for a query that filters on city and a different column, and a statistic on columns that are not correlated adds ANALYZE cost with no planning gain. Compare the statistics definitions in pg_statistic_ext with the WHERE and JOIN clauses of the queries that are slow, and drop objects that no plan uses.

Estimates used in place of query fixes

Statistics adjust what the planner believes about row counts, but they cannot make a query that scans too much rows fast. Some slow queries need a rewrite, a suitable index, or a change to the application's filter. If a plan is still poor after the statistics change, look at the query text and index choices before adding more statistics. Treat statistics as one input to the fix, and record which query each object was meant to help.

Extended statistics ignored for a query shape

The planner does not use every extended statistic it has. Dependency statistics apply to simple equality conditions on the columns involved, and the planner may skip them for expressions, ranges, or OR clauses. A query that looks like the one you tuned can still get the old plan. Run EXPLAIN ANALYZE on the exact query text your application sends, and confirm the estimate moved before you call the change complete.

How the tuning loop moves from slow query to verified plan

The loop starts with a slow query and an EXPLAIN ANALYZE plan that shows a large gap between estimated and actual row counts. The reader then chooses one of three fixes: extended statistics for correlated columns, a higher per-column statistics target for skewed values, or a query or index change. After creating the object and running ANALYZE on the table, the reader re-runs EXPLAIN and checks whether the estimate now tracks reality. If the gap remains, the loop returns to the decision step rather than stopping.

Decision loop from a slow query to a plan whose row estimates match actual rows.

Access and operational controls for statistics changes

Extended statistics are cheap to create but still schema changes that alter how the planner costs queries in production. The cards below cover who may create them, how changes move through review, how plan changes are recorded, and how statistics are checked during migrations and upgrades.

Who may create statistics

Running CREATE STATISTICS requires that you own the table, and ALTER TABLE for per-column targets follows the same ownership rule. Decide in advance which role holds these rights, usually the table owner or a privileged deployment role, and keep application roles out of it. Check that the owner role is the one your change pipeline uses, so that a statistics change does not fail mid-release because the wrong account ran it. Confirm the exact privilege rules for your version in the CREATE STATISTICS reference.

High availability docs

Schema change control on production

Treat each CREATE STATISTICS and ALTER TABLE ... SET STATISTICS statement as a schema change that goes through the same review as an index. Record the object name, the table, the column list and the statistic kinds in the change ticket, and state the expected query paths it should help. Plan the run window, because creating statistics and then the next ANALYZE both consume I/O on large tables. Keep the rollback as a documented DROP STATISTICS statement.

Logging and review of plan changes

Before the change, capture EXPLAIN ANALYZE output for the affected queries from a representative environment, and store it with the ticket. After the change and a fresh ANALYZE, capture the same queries again and compare estimated against actual row counts. Enable slow query logging or use pg_stat_statements so that a plan regression shows up as a timing change rather than a surprise report from users. Record the statistics object name alongside the query so a later reviewer can tell which change altered the plan.

Statistics in migration checks

Add a step to every migration runbook that lists the extended statistics objects in the source database and confirms they exist in the target. Schema dumps include them, but a rebuilt schema that is recreated by hand may drop them silently. After a restore or logical replication cutover, run ANALYZE on the affected tables and rerun the captured query set. Compare the plans with the pre-migration evidence, not just the response times.

Verify plans after major upgrades

PostgreSQL 18 pg_upgrade retains planner statistics across major upgrades, so the optimizer starts with the numbers it had before the upgrade. That does not prove the plans are unchanged, because the planner itself and its defaults change between versions. Rerun your captured query set on the new version, check that the extended statistics objects still exist and are in use, and compare plans against the pre-upgrade evidence. Plan this verification as part of the upgrade acceptance test, not as an optional follow-up.

PostgreSQL 18 release notes

Ownership of the statistics catalog

Assign one team to own the list of extended statistics objects, their reasons and the queries they serve. Without this record, later teams cannot tell whether a statistic is still needed after a query is rewritten or a column is dropped. Review the list during each major upgrade and during regular schema reviews, and remove objects whose queries no longer run. Ask your implementation partner or internal DBA to include this inventory in the handover documentation.

Questions teams ask before fixing query plans with extended statistics

How much effort does fixing a bad query plan with extended statistics take?

Usually less than a schema change, but more than a single setting. The effort depends on how many queries are affected, how many column pairs or groups are correlated, and whether the fix is confirmed on each query's plan before and after the change. Most of the time goes to finding the misestimated row counts in EXPLAIN ANALYZE output, choosing which statistics object fits each correlation, running ANALYZE on the table, and rechecking the plans under realistic data. Extended statistics are cheap to create and remove, so the main cost is analysis and verification rather than the change itself. Ask for the list of queries in scope and the test method before accepting a quote.

Can an in-house DBA fix bad query plans with extended statistics?

Yes, if the DBA has access to the database, can read EXPLAIN ANALYZE output, and can test changes outside production. The core tasks are standard: identify estimate errors, create a CREATE STATISTICS object with the dependencies, ndistinct or mcv kind that matches the correlation, and rerun ANALYZE. Teams usually need help when many applications share the database, when query text is generated by an ORM, or when the planner's choices interact with memory and parallel settings. An outside partner can supply a second review of the plans and a repeatable test procedure.

How long does the work take, and what sets the duration?

The duration depends on the number of slow queries in scope, the number of tables involved, and how long it takes to get a representative test copy and to repeat ANALYZE runs on it. Each candidate statistics object needs a before and after EXPLAIN check, and any change to a statistics target also needs a check of planning time and of ANALYZE duration on large tables. Teams with a clear list of problem queries and a current test copy move faster. Ask for a fixed timeline in the written scope rather than an open-ended estimate.

What does the work need from our team?

The work needs four inputs from your team:

  • EXPLAIN ANALYZE output for each slow query, with the database version and settings used
  • Read access to the schema, the query text and the table statistics views
  • A test copy with data distribution close to production, so the planner sees realistic row counts
  • A named contact who can approve changes to the statistics objects and to default_statistics_target on the affected columns

Without a test copy, results may not match production, and without query text, the correlation cannot be confirmed.

When should we bring in an outside partner for query plan fixes?

Bring in a partner when the slow queries span several applications, when the database has a large number of tables with correlated columns, or when an internal team lacks time to build a test procedure. A partner is also useful when a fix must be documented for audit or change control. DeployOpen implements and tests PostgreSQL performance changes in infrastructure you control, and delivers the statements, the before and after plans and the rollback steps as part of a fixed-scope engagement. Your team keeps ownership of the production change.

Do extended statistics replace indexes or query rewrites?

No. Extended statistics only improve the planner's row estimates for combinations of columns. They do not create access paths, so a missing index or a query that filters in an inefficient way will still need its own fix. In some cases, correct estimates let the planner choose an index it already had, and in other cases the best fix is a rewrite that removes a redundant predicate or an unnecessary join. Check each query's plan after the statistics change to decide whether an index or rewrite is still needed.

What risks come with changing planner statistics?

The main risk is a plan change that is faster for one query and slower for another, so every change should be checked against the full set of important queries. Statistics collection can also add time to ANALYZE on large tables, and the extra statistics data adds a small cost to planning. Confirm the effect on your production workload, keep the previous statistics definitions recorded, and check that autovacuum and analyze runs still complete on schedule.

What your team should decide before and after the change

Before any CREATE STATISTICS statement runs, record which queries justify the change. Start from the plans you already have: a query whose estimated row count is far from its actual row count in EXPLAIN ANALYZE, a join or aggregate that switches strategy on small data changes, or a slow query that a pg_stat_statements review has already ranked high. Write down the query text, the table and column combinations involved, and the business reason the query matters. A correlated-column fix that improves one report but adds planning work to a hot OLTP path is a trade-off, and the decision should say which workload wins. Also decide who owns the statistics objects. Someone must be accountable for the list of extended statistics, for reviewing them when the schema changes, and for dropping any object whose query has been removed. Extended statistics belong in schema migrations under version control, not in ad hoc changes on the primary, so the owner should be the team that reviews those migrations.

Test the change on a copy of production data before it reaches the primary. The statistics the planner uses come from ANALYZE over the actual value distribution, so a copy with synthetic or small data will mislead you. Confirm with your data owners how fresh and how representative the copy must be, and whether it contains personal data that needs masking under your own policies. Run the same query before and after creating the object, after running ANALYZE on the table in each case, and keep the plans. Confirm the planner version and settings match production, since a different PostgreSQL major version or a changed default_statistics_target can change the result. Then judge success from EXPLAIN ANALYZE across several runs and parameter values, not from one timing. Look at whether estimated and actual row counts converge, whether the join method changes for the right reason, and whether buffer counts and the plan shape are stable when parameters change. A single faster run can come from a warm cache. Record the result, including plans that did not improve, so the next review starts from evidence.

How DeployOpen scopes and verifies PostgreSQL plan fixes

DeployOpen approaches bad query plans caused by correlated columns as a scoped change to your own PostgreSQL environment, not a settings experiment. Each engagement starts from the specific queries, plans and statistics involved, and ends with before-and-after EXPLAIN evidence that your database team can review and repeat.

How we scope

  • Agree in writing which slow queries, tables and column groups are in scope before any change is made.
  • Collect current EXPLAIN ANALYZE output, row estimate gaps and PostgreSQL version details from your environment.
  • Confirm which statistics objects, statistics targets and maintenance windows your change control process allows.
  • Engagements are fixed-scope, so deliverables and timelines are set out in the written scope before work starts.

How we build

  • Create extended statistics for dependencies, n-distinct and MCV lists on the column groups the plans show are misestimated.
  • Adjust per-column statistics targets only where the evidence supports it, and record each change with its reason.
  • Run ANALYZE on the affected tables and compare plans against a copy of your production-like data where possible.
  • Test the change against representative workloads so that other queries sharing those tables are checked for regressions.

How we hand over

  • Deliver a written record of each statistics object, its definition, the target tables and the reason it was created.
  • Provide before and after EXPLAIN ANALYZE output for each fixed query, with estimated and actual row counts side by side.
  • Document the ANALYZE and maintenance steps your team needs to keep the statistics current after schema or data changes.
  • Walk your database engineers through the rollback steps, including how to drop a statistics object safely.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers for teams that want help after handover.
  • Recheck the affected plans after PostgreSQL minor and major upgrades, since planner behavior can change between versions.
  • Confirm with your team which monitoring signals, such as slow query tracking, will show when estimates drift again.
  • Review new column correlations as the schema grows, so that future statistics changes are planned rather than reactive.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.