Skip to content
mentoor

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?

Choose one answer

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

  1. 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 an UPDATE or DELETE in production without a transaction you roll back.
  2. Find the expensive node. Look at actual time and rows. A Seq Scan that reads 2,000,000 rows to return 12 is the usual suspect.
  3. Compare estimate with reality. If the planner expected 10 rows and found 100,000, statistics are stale; run ANALYZE on the table.
  4. 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.
  5. Rerun and compare. The Seq Scan should become an Index Scan or Index 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 on customer_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 on email. 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?

Choose one answer

Check yourself · 3 of 3

A query uses WHERE customer_id = ? ORDER BY created_at DESC LIMIT 20. Which index is best?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic