Sub topic 2
Checking Whether the Planner Uses an Index
This chapter assumes you can write basic SQL and know that an index speeds up lookups. Reading EXPLAIN output is helpful, but the chapter introduces what you need. Every later chapter relies on the checks here. Creating an index does not guarantee the planner will use it, so you need a way to find out.
What the planner decides
PostgreSQL does not run a query as written. The planner builds several candidate plans, estimates the cost of each from table statistics, and runs the cheapest. A sequential scan, an index scan, and a bitmap scan can all answer the same query. The planner picks one by estimated cost, so an index is used when the planner expects it to be cheaper, not whenever it is possible.
EXPLAIN shows the chosen plan. It does not show the plans that lost.
Preparing data worth testing
On a table with ten rows, a sequential scan is always cheapest, and any index looks unused. Test on realistic volume. These statements create the running schema, load 500,000 synthetic orders, and index them:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total_cents integer NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO orders (customer_id, status, total_cents, created_at)
SELECT (random() * 999)::int + 1,
(ARRAY['pending','paid','shipped','cancelled'])[1 + (random() * 3)::int],
(random() * 50000)::int,
now() - random() * interval '365 days'
FROM generate_series(1, 500000);
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
ANALYZE orders;ANALYZE collects the statistics the planner reads: row counts, value distributions, and most common values. Autovacuum normally does this in the background, but right after a bulk load it may not have run yet. Stale statistics are a frequent reason for surprising plans.
Reading a basic plan
Run EXPLAIN on a query the index was designed for:
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;The output has this shape. Your cost numbers will differ.
Limit (cost=0.42..30.1 rows=20 width=34)
-> Index Scan using orders_customer_created_idx on orders (cost=0.42..780.5 rows=500 width=34)
Index Cond: (customer_id = 42)Read the plan from the innermost, most indented node outward. The Index Scan using orders_customer_created_idx line names the index. Index Cond lists the conditions the index itself evaluates. There is no Sort node, because the index already returns rows in created_at DESC order for one customer.
The cost=a..b pair is the estimated startup cost and total cost in arbitrary units. The rows value is the estimated row count. Neither is a measurement.
Scan node types
| Node | Meaning |
|---|---|
| Seq Scan | Reads the whole table and filters each row. |
| Index Scan | Walks the index and fetches each matching row from the table. |
| Index Only Scan | Answers from the index alone, if the table pages are marked all-visible. |
| Bitmap Index Scan with Bitmap Heap Scan | Collects matching row locations from the index, then reads table pages in physical order. |
A Bitmap scan is a normal and healthy choice when a query matches a moderate share of rows. The planner often picks it between a plain index scan, which suits few rows, and a sequential scan, which suits many.
Filter versus Index Cond
Two labels tell you where a condition was applied:
Index Condmeans the condition was used to navigate the index.Filtermeans the condition was checked against rows after they were fetched.
An index can be used and still be poor. If your plan shows Index Cond: (customer_id = 42) and a Filter on another column, the index narrowed the search by one column only. Look for the columns you expected in Index Cond.
Measuring with EXPLAIN ANALYZE
Plain EXPLAIN shows estimates. EXPLAIN ANALYZE runs the query and adds actual times and row counts:
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;Compare rows= (estimate) with actual ... rows= on each node. A large gap, such as an estimate of 10 against an actual 100,000, means the statistics misled the planner. Run ANALYZE on the table, then check whether the plan changes.
The BUFFERS option adds shared hit and read counts: pages found in cache and pages fetched from outside it. Fewer buffers touched generally means less work, and this number is steadier than timing from run to run.
Index Only Scans and the visibility map
An Index Only Scan can skip the table only for pages the visibility map marks as all-visible. VACUUM maintains that map. On a freshly loaded or heavily updated table, the plan may show Heap Fetches: 48213, meaning the scan still visited the table for those rows. Run VACUUM orders; and check again. Chapter material on INCLUDE columns builds on this behavior.
Why the planner may ignore your index
Work through these causes in order. Most missing-index cases fall into one of them.
- The query does not match the index. For a B-tree multicolumn index, the query must constrain the leading columns. A filter only on
created_atcannot useorders_customer_created_idxefficiently. - The expression differs. An index on
lower(email)is not considered forWHERE email = 'x', and the reverse is also true. The query must contain the same expression. - The predicate is not implied. A partial index is usable only if the query's conditions imply the index's
WHEREclause. - The condition matches too many rows. If a filter returns a large share of the table, reading it sequentially is cheaper than thousands of random index lookups. This is correct planner behavior.
- The table is small. Under a few thousand rows, a sequential scan over a handful of pages beats any index.
- Statistics are stale. Run ANALYZE and compare again.
- Types do not match. A comparison that forces a cast on the indexed column can prevent index use. Cast the constant, not the column.
Forcing the question
To learn whether an index is possible for a query rather than preferred, disable the competing plan type for one transaction:
BEGIN;
SET LOCAL enable_seqscan = off;
EXPLAIN
SELECT * FROM orders
WHERE created_at > now() - interval '1 day';
ROLLBACK;SET LOCAL lasts only until the transaction ends. Despite the name, enable_seqscan = off does not forbid sequential scans. It adds a very large cost penalty to them, so one is still used when no alternative exists.
Now interpret the result. If the plan still shows a Seq Scan, no usable index exists for that query. If it switches to an index, the index is usable but the planner judged it more expensive. Compare the two total costs and actual timings with EXPLAIN ANALYZE before deciding anything.
Checking usage across the whole workload
EXPLAIN tests one query. To see whether an index earns its keep over time, read the statistics view:
SELECT indexrelname, idx_scan, idx_tup_read
FROM pg_stat_user_indexes
WHERE relname = 'orders';An idx_scan of 0 after a representative period of traffic suggests the index is unused. The counters reset when statistics are reset, so confirm how long they have been accumulating before dropping anything. Unused indexes still cost writes and storage, as a later chapter covers.
A repeatable checklist
The following flow summarizes the process.
Putting it together
Run the two queries from the multicolumn example and read each plan:
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
EXPLAIN SELECT * FROM orders WHERE created_at > now() - interval '1 day';The first constrains the leading column and should show Index Cond: (customer_id = 42), likely under a Bitmap Index Scan because about 500 rows match. The second does not constrain the leading column. Expect a Seq Scan. If the table were far larger and the condition very selective, the planner might still scan the whole index, which is slower than a dedicated index would be.
Exercise
You run EXPLAIN on a query and see a Seq Scan, although you created an index on the filtered column. List the checks you would make, in order, to find out whether the index is unusable or merely not preferred.
Show answer
First confirm the table is large enough and statistics are current by running ANALYZE. Then check that the query matches the index: leading column constrained, same expression, and conditions that imply any partial-index predicate. Next, inside a transaction run SET LOCAL enable_seqscan = off and EXPLAIN again. If the plan still uses a Seq Scan, the index cannot serve the query. If it now uses the index, the index is usable and the planner chose the sequential scan on cost, so compare costs and actual times with EXPLAIN ANALYZE, and check how many rows the condition matches.
Exercise
In EXPLAIN ANALYZE output, a node shows rows=10 estimated but actual rows=120000. What does this suggest, and what is the first step you take?
Show answer
The planner's statistics do not describe the data, so its cost estimates are unreliable and it may choose a poor plan. Run ANALYZE on the table, then re-run EXPLAIN ANALYZE and see whether the estimate and plan improve.