Reading a slow query plan before adding an index
When a query is slow, the first instinct is to add an index on whatever column is in the WHERE clause. Sometimes that works. Other times the database ignores it, and you keep paying for it on every write from then on. Read the plan first. The examples here are PostgreSQL, but the same thinking applies to Oracle's DBMS_XPLAN and MySQL's EXPLAIN ANALYZE.
Get a plan with real numbers
Plain EXPLAIN only shows estimates. ANALYZE runs the query and reports what actually happened:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 4217
ORDER BY created_at DESC
LIMIT 20;
Because ANALYZE executes the statement, wrap anything that changes data in a transaction you roll back.
Here's the shape of a plan you might get back:
Limit (cost=48211.20..48211.25 rows=20 width=24) (actual time=412.8..412.8 rows=20 loops=1)
Buffers: shared hit=1204 read=38110
-> Sort (cost=48211.20..48223.70 rows=5000 width=24) (actual time=412.8..412.8 rows=20 loops=1)
Sort Key: created_at DESC
Sort Method: top-N heapsort Memory: 27kB
-> Seq Scan on orders (cost=0.00..48078.00 rows=5000 width=24) (actual time=0.03..408.1 rows=5312 loops=1)
Filter: (customer_id = 4217)
Rows Removed by Filter: 2994688
Read it from the innermost node outward. Each node feeds the one above it.
The four things I look for
Where the time goes. actual time is cumulative for a node, including its children. Here the scan takes 408 ms of 412 ms, so changing the sort would be wasted effort.
Rows removed. Rows Removed by Filter: 2994688 means the database read about three million rows to keep about five thousand. That's the signature of a missing or unusable index.
Estimates against reality. Compare rows=5000 with actual rows=5312. Those are close, so the planner understands this data. If the planner expected 10 rows and got 500,000, it probably chose the wrong plan, and an index won't necessarily fix that. Run ANALYZE orders, and consider more statistics for that column or extended statistics for correlated columns.
Buffers. read=38110 is 38,110 pages fetched from outside PostgreSQL's cache, about 300 MB at the default 8 kB page size. Timing depends on what happens to be cached, but buffer counts are much more stable, which makes them better for comparing before and after.
Now choose the index
For this query, an index on customer_id alone would find the rows, but it would still sort them. A composite index can do both jobs:
CREATE INDEX CONCURRENTLY orders_customer_recent_idx
ON orders (customer_id, created_at DESC);
The column order matters: equality columns first, then the range or sort column. With this index, the database jumps to the customer and reads the first 20 entries already in order. The sort node disappears, and LIMIT can actually stop early.
Use CONCURRENTLY on a live table so that writes aren't blocked. It can't run inside a transaction, and if it fails it leaves an invalid index behind that you have to drop.
Two variations are worth knowing:
-- Only the rows you ever query: smaller, and cheaper to maintain.
CREATE INDEX orders_unpaid_idx ON orders (customer_id) WHERE status = 'UNPAID';
-- Includes the selected column, so an index-only scan can skip the table.
CREATE INDEX orders_customer_cover_idx ON orders (customer_id, created_at DESC) INCLUDE (total);
When an index won't help
Check for these before adding anything:
- A function or cast on the column.
WHERE lower(email) = ?can't use an index onemail. Either create an index on the expression, or change the query. - A type mismatch. Comparing a
varcharcolumn with a numeric parameter, or passing the wrong type through an ORM, can force a conversion that rules the index out. - A leading wildcard.
LIKE '%term'can't use a B-tree. A trigram GIN index can. - A query that returns much of the table. A sequential scan really is faster in that case. The planner is right, and the fix is to ask for less.
- OR across different columns. Sometimes rewriting as
UNION ALLgives a far better plan. - OFFSET pagination.
OFFSET 100000reads and throws away 100,000 rows no matter what you index. Paginate by key instead.
Confirm it, then count the cost
Run the same EXPLAIN (ANALYZE, BUFFERS) again. The node type should change, the rows removed should fall, and buffers should drop dramatically. If they don't, drop the index.
Every index costs storage and slows writes, and in PostgreSQL it can also prevent HOT updates. So check occasionally that the ones you have are earning their place:
SELECT relname, indexrelname, idx_scan
FROM pg_stat_user_indexes
ORDER BY idx_scan ASC
LIMIT 20;
An index with zero scans over a representative period is a candidate for removal, after checking replicas and any monthly jobs.
Reading a plan takes minutes, and it changes the question from "which index should I add?" to "why is this query reading so much?"