Backend Engineering
Why your PostgreSQL query is slow: the indexing basics that fix most problems
Read EXPLAIN ANALYZE, understand sequential versus index scans, order composite indexes correctly, and use partial and covering indexes without over-indexing.
By Envexa Engineering7 min read
Most slow-query problems in a growing application have the same cause: PostgreSQL is reading far more rows than it needs to. Indexes fix that, but guessing at them wastes time and slows writes. A handful of principles, applied with measurement, solves the majority of cases.
Start by measuring, not guessing
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total FROM orders
WHERE customer_id = 42 AND status = 'paid'
ORDER BY created_at DESC
LIMIT 20;EXPLAIN ANALYZE actually runs the query and reports the plan with real timings. Look for a sequential scan on a large table, a large gap between estimated and actual row counts, and a sort that spills to disk. BUFFERS shows how much data was read, which is often the real cost.
Sequential scan versus index scan
A sequential scan reads the whole table. An index scan jumps to matching rows. Neither is always better: for a tiny table, or a query returning a large share of the rows, a sequential scan is cheaper, and PostgreSQL will rightly choose it. Indexes pay off when the query is selective, returning a small fraction of the table.
Composite indexes: order matters
CREATE INDEX idx_orders_customer_status_created
ON orders (customer_id, status, created_at DESC);An index on (customer_id, status, created_at) is useful for queries that filter on customer_id, or on customer_id and status, and it can also satisfy the ordering. It does not help a query that filters only on status, because the leading column is missing. A good rule: put equality-filtered columns first, then the column used for ranges or sorting.
Partial and covering indexes
- Partial index. Index only the rows you query.
CREATE INDEX ... ON orders (created_at) WHERE status = 'pending'is small and fast if you mostly look up pending orders. - Covering index. With
INCLUDE, an index can hold extra columns so PostgreSQL can answer from the index alone (an index-only scan), avoiding table lookups:CREATE INDEX ... ON orders (customer_id) INCLUDE (total).
Things that quietly defeat an index
- Functions on the column, like
WHERE lower(email) = 'a@b.com', unless you create an index on that expression. - Type mismatches that force a cast on the indexed column.
- Leading wildcards, such as
LIKE '%term', which a standard B-tree cannot use. - Stale statistics. Make sure autovacuum and autoanalyze are running so the planner has accurate row estimates.
- The N+1 pattern. One query per row from application code looks cheap each time but adds up. Fetch related rows in one query with a join or
INlist.
Indexes are not free
Every index must be updated on each insert, update and delete, and takes disk and memory. Index for the queries you actually run. Periodically check pg_stat_user_indexes for indexes with no scans and drop them. Foreign-key columns are not indexed automatically in PostgreSQL, so index those you join on or filter by.
Adding indexes to a live system
A plain CREATE INDEX blocks writes while it builds. On a table in use, use CREATE INDEX CONCURRENTLY, which avoids that (and cannot run inside a transaction block). We cover the wider approach in zero-downtime database migrations.
Frequently asked questions
Why is PostgreSQL not using my index?
Common reasons: the table is small enough that a sequential scan is cheaper, the query does not match the index's leading column, a function or type cast on the column prevents use, or statistics are out of date. EXPLAIN shows what the planner chose.
How many indexes are too many?
Each index slows inserts and updates and consumes space and memory. Index for your real query patterns and drop indexes that pg_stat_user_indexes shows are unused.
Should I index every foreign key?
Usually yes for columns you join or filter on, and certainly where you delete or update parent rows, because PostgreSQL does not create indexes on foreign-key columns automatically.
Related articles
Zero-downtime database migrations: the expand and contract pattern
Change your PostgreSQL schema without downtime: expand and contract, safe index creation, lock timeouts, batched backfills and a pre-deploy checklist.
Idempotency keys: designing APIs that are safe to retry
Networks fail and clients retry. How idempotency keys prevent duplicate charges and orders, with implementation, edge cases and storage design.