Sub topic 14
Fixing a slow plan: indexes, statistics and rewrites
This chapter assumes you can run EXPLAIN and EXPLAIN (ANALYZE, BUFFERS) in PostgreSQL. It also assumes you can read a plan tree and know the scan and join node types. You have already found the node that costs the most. Now you choose a fix.
Match the symptom to the fix
A slow plan usually falls into one of three groups. Each group has its own fix, so diagnose before you change anything.
| Symptom in the plan | Likely cause | First fix to try |
|---|---|---|
| Sequential scan that discards most rows (large "Rows Removed by Filter") | No usable index for the filter | Add or adjust an index |
| Estimated rows far from actual rows | Stale or too-coarse statistics | Refresh or extend statistics |
| Index exists but is not used, or a large sort or hash spills to disk | Query shape defeats the index, or memory is too small | Rewrite the query or adjust settings |
Always finish by running the same EXPLAIN again. A fix that you did not measure is a guess.
Fix 1: add an index
Start with the simplest case. A query filters on a column that has no index, so the planner scans the whole table.
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42;If the plan shows Seq Scan on orders with a Filter: (customer_id = 42) line, and the table is large, an index on customer_id can help. Create it, refresh statistics, and look again.
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
ANALYZE orders;
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42;You should now see an Index Scan or Bitmap Heap Scan using orders_customer_id_idx. The estimated cost should be much lower.
When the planner still ignores the index
Creating an index does not force its use. The planner compares costs and may keep the sequential scan for good reasons.
- The filter matches a large share of the table. Reading most pages through an index costs more than reading them in order.
- The table is small. A sequential scan of a few pages is cheap.
- Statistics are stale, so the planner believes the filter matches many rows.
- The query wraps the column in a function or expression, so the index on the plain column cannot match.
You can test whether the index would help by turning off sequential scans for one session. Use this only for diagnosis.
BEGIN;
SET LOCAL enable_seqscan = off;
EXPLAIN (ANALYZE)
SELECT *
FROM orders
WHERE customer_id = 42;
ROLLBACK;SET LOCAL lasts only until the transaction ends. If the forced index plan is faster, the planner's cost estimates are off and the cause is probably statistics. If it is slower, the planner was right.
Choose the right kind of index
A few design choices matter more than the decision to index at all.
- Multicolumn indexes. For
WHERE customer_id = 42 AND status = 'open', an index on(customer_id, status)serves both conditions. Put equality columns first. A query that filters only on the second column cannot use the index efficiently. - Sort order. For
WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10, an index on(customer_id, created_at)can return rows already sorted. The plan then drops theSortnode and stops after ten rows. - Covering indexes. Adding columns with
INCLUDEcan turn anIndex Scaninto anIndex Only Scan, which avoids visiting the table. This works best when the table is vacuumed regularly, because index-only scans depend on the visibility map. CheckHeap FetchesinEXPLAIN ANALYZE. A high number means the visibility map is out of date. - Partial indexes. If most queries ask only for open orders,
CREATE INDEX ... WHERE status = 'open'is smaller and faster to maintain than a full index.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC)
INCLUDE (status);Every index has a price. Each INSERT, UPDATE and DELETE must update every index on the table, and indexes take disk space. Add the index that fixes a measured problem, not every index that might help.
Fix 2: repair the statistics
If estimated rows and actual rows differ by a factor of ten or more, the planner chose its plan on wrong information. A wrong estimate can pick a nested loop where a hash join belongs, or the reverse. Fixing the estimate often fixes the plan with no index change.
Refresh stale statistics
PostgreSQL stores per-column statistics that the planner reads when it estimates rows. You can inspect them in the pg_stats view.
SELECT attname, n_distinct, null_frac
FROM pg_stats
WHERE tablename = 'orders';Autovacuum normally runs ANALYZE for you. After a bulk load or a large delete, the statistics can lag behind the data. Run ANALYZE orders; by hand and compare the plan again.
Raise the statistics target for skewed columns
ANALYZE samples the table and keeps a limited number of common values and histogram buckets per column. The default target is 100. A column with many distinct values, or a very uneven distribution, may need more detail.
ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 500;
ANALYZE orders;A higher target makes ANALYZE slower and the planner's work slightly heavier, so raise it only for columns that show misestimates.
Tell the planner about correlated columns
By default the planner assumes that columns are independent. For WHERE city = 'Leeds' AND zip_code = 'LS1', it multiplies the two selectivities. If every LS1 row is in Leeds, the result is far too small. Extended statistics fix this.
CREATE STATISTICS orders_city_zip_stats (dependencies)
ON city, zip_code FROM orders;
ANALYZE orders;After ANALYZE, the estimate for the combined filter should move closer to the real count. Other kinds of extended statistics include ndistinct, for GROUP BY on several columns, and mcv, for common value combinations.
Fix 3: rewrite the query
Sometimes the plan is slow because the query asks the database to do something that an index cannot support. Rewriting keeps the same result but gives the planner a better option.
Do not hide the column inside a function
An index on created_at cannot serve a filter on date_trunc('day', created_at), because the index stores the raw column, not the result of the function.
-- Prevents use of an index on created_at
SELECT count(*)
FROM orders
WHERE date_trunc('day', created_at) = DATE '2026-03-01';
-- Lets the planner use an index on created_at
SELECT count(*)
FROM orders
WHERE created_at >= DATE '2026-03-01'
AND created_at < DATE '2026-03-02';If you cannot change the query, create an expression index on date_trunc('day', created_at) instead.
Avoid type mismatches and leading wildcards
Comparing a column to a value of a different type can add a cast to the column, which blocks the index. A LIKE '%smith' pattern has no fixed start, so an ordinary B-tree index cannot help. Use a trigram index (the pg_trgm extension) for that case.
Fetch fewer rows and fewer columns
- Replace
SELECT *with the columns you need. This makes index-only scans possible and reduces row width. - Add
LIMITwhen you only need the first rows, and anORDER BYindex to match. - Filter before you join or aggregate when the filter does not change the result.
Replace deep `OFFSET` with keyset pagination
OFFSET 100000 still reads and discards 100000 rows. Use the last seen key instead.
SELECT id, created_at
FROM orders
WHERE (created_at, id) < (TIMESTAMP '2026-03-01 12:00:00', 98765)
ORDER BY created_at DESC, id DESC
LIMIT 20;With an index on (created_at, id), each page costs about the same no matter how deep you go.
Test a fix on a write statement safely
When the slow statement is an UPDATE or DELETE, EXPLAIN ANALYZE executes it. Wrap the test in a transaction and roll back.
BEGIN;
EXPLAIN (ANALYZE)
UPDATE orders
SET status = 'archived'
WHERE created_at < DATE '2020-01-01';
ROLLBACK;Note that the rolled-back statement still takes locks while it runs and can generate dead rows that vacuum must clean up later. Test on a copy or a quiet system when you can.
Check that the fix worked
Compare the before and after plans on the numbers that matter.
- Execution time at the bottom of the
EXPLAIN ANALYZEoutput. - Estimated versus actual rows on the node you changed.
Buffers: shared hitandreadcounts. Fewer buffers means less work.- Whether the node type changed in the way you expected.
Run the query two or three times. The first run may read from disk and later runs from cache, so compare like with like. A fix that helps on a small test table may behave differently on production-size data, so test with realistic volume.
Exercise
A query SELECT * FROM orders WHERE city = 'Leeds' AND zip_code = 'LS1' estimates 12 rows but returns 40,000. A sequential scan is used and the index on city is ignored. Name two fixes in the order you would try them, and say why you would not start by adding more indexes.
Show answer
First, create extended statistics on (city, zip_code) with the dependencies kind and run ANALYZE. The estimate is wrong because the planner treats the two columns as independent, and the plan was chosen on that wrong number. Second, if the estimate is still off, raise the statistics target on the affected columns with ALTER TABLE ... SET STATISTICS and run ANALYZE again. Adding indexes first is wrong because the actual row count is large (40,000), so a sequential scan may be the correct choice, and extra indexes add write cost without fixing the misestimate.
Exercise
A report filters with WHERE date_trunc('month', created_at) = DATE '2026-03-01' and uses a sequential scan even though created_at is indexed. Rewrite the filter so the index can be used.
Show answer
Use a range on the raw column: WHERE created_at >= DATE '2026-03-01' AND created_at < DATE '2026-04-01'. The index stores created_at values, not the output of date_trunc, so only a condition on the plain column can use it. An expression index on date_trunc('month', created_at) is the alternative when the query cannot be changed.