Topic 4 of 5 · 5 min read
Indexes and reading query plans
Goal: Read an EXPLAIN ANALYZE plan, name the slow step and propose one index that removes it, stating its cost on writes.
An index is a sorted copy of one or more columns that lets the database jump to rows instead of reading the whole table. Read EXPLAIN ANALYZE to see what the database really did, then add the smallest index that removes the slow step.
Check yourself · 1 of 3
A plan shows 'Seq Scan on orders ... Rows Removed by Filter: 1999982' for a query returning 18 rows. What does it tell you?
Why it matters
A query that takes 5 ms on a thousand rows can take minutes on fifty million. The code is the same. What changed is that the database now reads every row. Knowing how to read a plan turns "the page is slow" into one named step.
How to do it
- Run the plan with real timing. In PostgreSQL,
EXPLAIN (ANALYZE, BUFFERS) SELECT .... Note that ANALYZE actually executes the statement, so do not run it on anUPDATEorDELETEin production without a transaction you roll back. - Find the expensive node. Look at
actual timeandrows. ASeq Scanthat reads 2,000,000 rows to return 12 is the usual suspect. - Compare estimate with reality. If the planner expected 10 rows and found 100,000, statistics are stale; run
ANALYZEon the table. - Add an index that matches the filter. For
WHERE customer_id = 7 AND status = 'paid' ORDER BY created_at, a composite index on(customer_id, status, created_at)works. Equality columns come first, the sort column last. - Rerun and compare. The
Seq Scanshould become anIndex ScanorIndex Only Scan, and the time should drop.
Before and after
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;
-- Seq Scan on orders (actual time=0.02..410.5 rows=18 loops=1)
-- Filter: (customer_id = 42)
-- Rows Removed by Filter: 1999982
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
-- Index Scan using orders_customer_id_idx (actual time=0.03..0.09 rows=18 loops=1)
What goes wrong
- Wrong column order. An index on
(status, customer_id)does not help a query that filters only oncustomer_id. A composite index is useful from its leftmost column. - A function on the column.
WHERE lower(email) = 'a@b.com'cannot use a plain index onemail. Index the expression or store the lowercase value. - Leading wildcard.
LIKE '%smith'cannot use a B-tree index. - An index for everything. Each index must be updated on every insert and update, and it takes disk space. Add one per proven slow query.
Examples
Column order in a composite index
Query: WHERE customer_id = ? AND created_at > ?.
CREATE INDEX a ON orders (customer_id, created_at); -- serves the query
CREATE INDEX b ON orders (created_at, customer_id); -- scans a date range first
The first narrows to one customer, then to a date range inside it. It also serves queries that filter on customer_id alone. The second does not.
Estimate versus actual
Hash Join (rows=10 ... actual rows=250000)
The planner expected 10 rows and got 250,000, so it chose a plan that suits 10. Run ANALYZE orders; to refresh the statistics and check the plan again before adding any index.
Key points
- EXPLAIN ANALYZE runs the statement and shows actual time and row counts for each step.
- A sequential scan that reads millions of rows to return a few is the usual sign of a missing index.
- In a composite index, put equality columns first and the sort column last; the leftmost column must appear in the filter.
- A function on the column or a leading wildcard stops a plain B-tree index from being used.
- Every index slows inserts and updates and uses disk, so add one for each proven slow query.
Common mistakes
- Adding an index without running EXPLAIN ANALYZE before and after.
- Putting the columns of a composite index in the wrong order.
- Wrapping the indexed column in a function in the WHERE clause.
- Running EXPLAIN ANALYZE on a DELETE or UPDATE in production, which really executes it.
Check yourself · 2 of 3
A query filters WHERE lower(email) = 'ana@example.com'. There is a plain index on email. Why is it not used?
Check yourself · 3 of 3
A query uses WHERE customer_id = ? ORDER BY created_at DESC LIMIT 20. Which index is best?
Practice items, not counted towards your mastery.
Start here
- PostgreSQL tutorial (opens in a new tab)DocsFree
Official walk-through of tables, joins, aggregates and transactions on a small schema.
- SQLBolt: interactive SQL lessons (opens in a new tab)CourseFree
Short browser exercises on filters, joins and aggregates with instant feedback.
- Use The Index, Luke: SQL indexing and tuning (opens in a new tab)BookFree
A free book on how indexes work and how to design them for real queries.
More for this topic
- Using EXPLAIN (PostgreSQL documentation) (opens in a new tab)DocsFree
How to read plan nodes, cost, actual time and row estimates, with worked output.