Skip to content

Why is my PostgreSQL query slow? Read EXPLAIN, then add an index

Use EXPLAIN ANALYZE to see whether PostgreSQL reads the whole table, add the right index, check the plan changes, and know when an index does not help.

Checked 2026-11-19

Before adding an index, ask PostgreSQL how it runs the query.

EXPLAIN shows the plan, ANALYZE runs it

EXPLAIN ANALYZE
SELECT * FROM orders WHERE customer_id = 42;

Look for the first line of the plan:

  • Seq Scan on orders means every row is read and tested. Fine for a small table, slow for a big one.
  • Index Scan or Bitmap Heap Scan means an index found the rows.

EXPLAIN on its own only estimates. EXPLAIN ANALYZE really runs the query and adds the actual time and row counts, so do not use it on an UPDATE or DELETE you do not want to happen (wrap it in BEGIN ... ROLLBACK).

Add an index on the column you filter by

CREATE INDEX orders_customer_id_idx ON orders (customer_id);
ANALYZE orders;
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;

ANALYZE refreshes the statistics the planner uses to choose. On a live production table, use CREATE INDEX CONCURRENTLY so writes are not blocked while it builds.

When an index does not help

  • The query returns most of the table. Reading the table straight through is cheaper than jumping through an index, and PostgreSQL knows it.
  • The column is wrapped in a function. WHERE lower(email) = 'a@b.com' cannot use an index on email; it needs an index on lower(email).
  • The table is tiny. The sandbox below has 500 orders, so PostgreSQL may keep the Seq Scan even with an index. That is the right choice, not a bug.
  • Multi-column order matters. An index on (store_id, status) helps WHERE store_id = 1 and WHERE store_id = 1 AND status = 'pending', but not WHERE status = 'pending' alone.

Every index also slows down writes and takes disk, so add the ones a real query needs.

Try it in your browser

Practise it on a real machineIndexes, Transactions & EXPLAIN lab
Open the lab