Hard postgresql sql

A query that was fast yesterday is slow today with no code change. How can statistics cause that?

The 30 second answer

The planner picks a plan from row estimates, and estimates come from sampled statistics gathered by ANALYZE. After a bulk update, a migration or skewed growth, those statistics can be stale or miss rare values, the estimate flips and so does the plan. I compare estimated and actual rows, run ANALYZE on the table, raise the statistics target for skewed columns, and add extended statistics for correlated columns.

Could you say this in an interview?

From the basics. For every column, ANALYZE stores a sample-based summary in pg_stats: the most common values with their frequencies, a histogram of the rest, the null fraction and the number of distinct values. The planner multiplies those fractions to guess how many rows each step returns, then picks the cheapest plan for that guess. default_statistics_target (default 100) controls how detailed the summary is and how many rows are sampled. Autovacuum runs ANALYZE when enough rows have changed since the last one, based on a threshold plus a fraction of the table.

Real incidents, as concrete scenarios.

  • Rare status values. Zalando's engineering blog (2015) describes stored procedures that sporadically hit statement timeouts. A status column had a few rare values (like NEW) and a huge majority (DONE). When the sample missed a rare value, the planner's estimate was far off: in their test, it assumed 332,111 rows for a value with 98 real rows, chose a bitmap heap scan, and the estimated cost was "20,000 times higher". Running ANALYZE often fixed it; the durable fix was a higher statistics target for that column.
  • Mass update. GitLab's public incident report (December 2020) describes a monthly job that touched almost all rows of a central namespaces table; the resulting statistics "caused poor query plans" and timeouts across the application. The short-term fix was ANALYZE on the table.
  • Auto-analyze flips a plan. Clerk's postmortem (February 2026) describes an automatic analyze whose sample saw only NULLs in a column that was 99.9996% NULL, so the planner assumed no non-null rows; the query actually returned over 17,000, and the outage lasted until ANALYZE was re-run manually. They then raised the statistics target and refactored the query.

What to do, step by step.

-- 1. Confirm: estimated rows far from actual rows in EXPLAIN (ANALYZE, BUFFERS)
-- 2. Look at what the planner knows
SELECT most_common_vals, most_common_freqs, null_frac, n_distinct
FROM pg_stats WHERE tablename = 'orders' AND attname = 'status';

-- 3. Refresh statistics now
ANALYZE orders;

-- 4. Make rare values visible in future samples
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000;
ANALYZE orders;

-- 5. Correlated columns (city and zip, brand and category): tell the planner
CREATE STATISTICS products_brand_cat (dependencies, ndistinct, mcv)
  ON brand_id, category_id FROM products;
ANALYZE products;

Why extended statistics. By default the planner assumes columns are independent and multiplies their selectivities. For brand_id = 7 AND category_id = 3 where brand 7 only sells in category 3, that underestimates badly. CREATE STATISTICS supports ndistinct, dependencies and mcv kinds for such column groups.

Trade-offs.

  • A higher statistics target makes ANALYZE slower and planning slightly more expensive. Raise it per column, not globally.
  • ANALYZE after every bulk load or migration is cheap insurance.
  • If a query's plan is unstable by nature, a partial index or a rewrite that leaves the planner one obvious choice is more robust than tuning statistics.

Alternate interview scenarios

"After a major-version upgrade, every dashboard is slow."

Statistics may be missing after the upgrade, depending on the method; run ANALYZE on the whole database before taking traffic. PostgreSQL 18's pg_upgrade retains optimizer statistics, according to its release notes; older versions needed an ANALYZE afterwards.

"A queue table with status NEW, PROCESSING and DONE slows down as it grows."

The rare statuses are a shrinking fraction. Use a partial index WHERE status <> 'DONE' so queries for open work stay small, and keep the column's statistics target high.

Sources (6)
  1. Zalando Engineering: Analyzing Extreme Distributions in PostgreSQL (July 2015)engineering.zalando.com
  2. GitLab production incident: "Reset CI minutes job" query timeouts (December 2020)gitlab.com
  3. Clerk: System outage postmortem (February 2026)clerk.com
  4. PostgreSQL docs: Statistics used by the plannerpostgresql.org
  5. PostgreSQL docs: CREATE STATISTICSpostgresql.org
  6. PostgreSQL docs: Routine vacuuming (the autovacuum analyze threshold)postgresql.org