Sub topic 14
Fixing a Slow Plan: Indexes, Statistics, and Rewrites
Assume you can write SELECT queries with WHERE, JOIN, GROUP BY, and ORDER BY, and that you know an index stores searchable values separately from table rows. This chapter uses PostgreSQL syntax.
A slow plan is usually caused by one of three problems:
- The query must inspect too many rows.
- The planner estimates the work incorrectly.
- The query asks for work that can be avoided or reduced.
Start by measuring the current plan:
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE customer_id = 42;Do not choose a fix from the SQL text alone. Check the plan, especially actual rows, execution time, and buffer usage.
Add an index for selective filters
An index helps when a condition matches a small part of a table. For example:
CREATE INDEX orders_customer_id_idx
ON orders (customer_id);
ANALYZE orders;Run the same EXPLAIN again. PostgreSQL might replace a sequential scan with an index scan. This is useful when customer_id = 42 returns few rows.
An index is less useful when most rows match. Reading the index and then fetching nearly every table row can cost more than scanning the table once. Indexes also consume storage and make INSERT, UPDATE, and DELETE slower because the index must be maintained.
A multicolumn index can support a query that commonly filters on the same columns:
CREATE INDEX orders_customer_date_idx
ON orders (customer_id, created_at);The column order matters. This index is most useful when the query restricts customer_id, then uses created_at for filtering or ordering.
Refresh statistics when estimates are wrong
PostgreSQL uses statistics to estimate how many rows each condition will match. After a large data change, those statistics may be stale.
ANALYZE orders;Compare estimated rows with actual rows in EXPLAIN (ANALYZE). A large difference can cause the planner to choose a poor join or scan method.
If two columns are correlated, ordinary statistics may not describe their relationship. For example, city and postal code are related:
CREATE STATISTICS orders_city_zip_stats (dependencies)
ON city, zip_code
FROM orders;
ANALYZE orders;This can improve estimates for predicates that use both columns.
Rewrite the query when it does unnecessary work
An index cannot fix work that the query requests unnecessarily. Select only needed columns instead of using SELECT *. Filter rows before joining when that makes the result smaller. Avoid applying a function to an indexed column when a range condition expresses the same test.
For example, this expression may prevent a normal index from helping:
SELECT *
FROM orders
WHERE DATE(created_at) = DATE '2026-01-15';A range condition keeps the column searchable:
SELECT *
FROM orders
WHERE created_at >= TIMESTAMP '2026-01-15 00:00:00'
AND created_at < TIMESTAMP '2026-01-16 00:00:00';Use a measured tuning loop
Make one change at a time. Confirm that execution time, row estimates, and buffer reads improve. Keep the change only if it helps representative data and real workloads.
Exercise
A query filters on customer_id, returns 80 percent of the table, and uses a sequential scan. Should you add an index automatically?
Show answer
No. A sequential scan may be cheaper when most rows are needed. Measure the plan and workload first.