Solving PostgreSQL Query Performance Problems
Read the plan, not the guesses: a workflow for diagnosing and fixing slow PostgreSQL queries.
- postgresql
- performance
- indexes
- sql
On this page ยท 14 sections
A slow query rarely announces itself. It shows up as an API endpoint that takes two seconds, a dashboard that times out, or a database CPU graph that climbs after a feature ships. The fix is almost never a magic setting. It is a workflow: find the expensive queries, read the plan, make a targeted change, and verify.
This guide walks through that workflow for PostgreSQL, with illustrative examples. Table names and plan output below are examples to show how to read plans; your numbers will differ, so always measure on your own data.
Step 1: Find the queries that matter
Do not guess. Ask the database which statements consume the most time.
Enable pg_stat_statements (it must be listed in shared_preload_libraries, which requires a restart), then create the extension:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;SELECT calls, round(total_exec_time::numeric, 1) AS total_ms, round(mean_exec_time::numeric, 2) AS mean_ms, rows, left(query, 100) AS queryFROM pg_stat_statementsORDER BY total_exec_time DESCLIMIT 10;Sorting by total time surfaces the queries that cost you the most overall: a 5 ms query called a million times often matters more than a 3-second query run once a day.
Also log slow statements as they happen:
-- postgresql.conf (or ALTER SYSTEM)log_min_duration_statement = 500 -- log anything slower than 500 msOn managed databases, these are usually exposed as parameters or a "slow query log" setting.
Step 2: Read the plan
EXPLAIN shows the plan. EXPLAIN (ANALYZE, BUFFERS) runs the query and reports reality:
EXPLAIN (ANALYZE, BUFFERS)SELECT id, total_cents, created_atFROM ordersWHERE customer_id = 4821 AND status = 'paid'ORDER BY created_at DESCLIMIT 20;An illustrative result for a table with no helpful index:
Limit (cost=18450.2..18450.3 rows=20) (actual time=212.4..212.5 rows=20 loops=1) -> Sort (cost=18450.2..18452.9 rows=1080) (actual time=212.4..212.4 rows=20 loops=1) Sort Key: created_at DESC -> Seq Scan on orders (cost=0.00..18120.0 rows=1080) (actual time=0.03..205.9 rows=1043 loops=1) Filter: ((customer_id = 4821) AND (status = 'paid')) Rows Removed by Filter: 1998957Planning Time: 0.2 msExecution Time: 212.7 msHow to read it:
- Plans are trees. Read from the innermost, most indented node outward.
costis the planner's estimate in arbitrary units;actual timeis real milliseconds (first row..last row).rowsestimated vs actual rows tells you whether the planner's statistics are accurate. A large gap, such as estimating 10 rows and getting 100,000, often explains a bad plan.Rows Removed by Filter: 1998957is the red flag here: the database read two million rows to keep about a thousand.loopsmultiplies per-loop time. A node withloops=5000andactual time=0.1still costs about 500 ms.BUFFERSshows how much data came from cache (shared hit) vs disk (read).
EXPLAIN ANALYZEexecutes the statement. ForUPDATEorDELETE, run it insideBEGIN; ... ROLLBACK;.
Common plan nodes
| Node | Meaning | Watch for |
|---|---|---|
Seq Scan | Reads the whole table | Fine for small tables; bad when it discards most rows |
Index Scan | Walks an index, fetches rows | Good for selective filters |
Index Only Scan | Answers from the index alone | Best case; needs a visibility map kept fresh by VACUUM |
Bitmap Heap Scan | Collects matches, then reads pages in order | Common middle ground for moderately selective filters |
Nested Loop | For each outer row, probe the inner side | Great with an index on the inner side; terrible without |
Hash Join | Builds a hash table of one side | Good for large joins; watch memory (work_mem) |
Sort | Sorts rows | Sort Method: external merge Disk means it spilled to disk |
Step 3: Fix with the right index
For the query above, the filter is two equality conditions and the sort is on created_at. A composite index matching equality columns first, then the sort column can serve both filtering and ordering:
CREATE INDEX CONCURRENTLY idx_orders_customer_status_created ON orders (customer_id, status, created_at DESC);CONCURRENTLY builds the index without blocking writes (it takes longer, and cannot run inside a transaction). After the index, the plan should become an Index Scan that stops after 20 rows, because the index already provides the order and LIMIT lets PostgreSQL stop early.
Rules of thumb for composite indexes:
- Put equality columns first, then range or sort columns.
- Column order matters: an index on
(a, b)helpsWHERE a = ?but generally notWHERE b = ?alone. - Match the sort direction when ordering by several columns.
Partial indexes
If you only ever query a subset, index only that subset. It is smaller and faster to maintain:
CREATE INDEX CONCURRENTLY idx_orders_open ON orders (customer_id, created_at DESC) WHERE status = 'open';Covering indexes
INCLUDE adds non-key columns so the query can be answered with an index-only scan:
CREATE INDEX CONCURRENTLY idx_orders_cover ON orders (customer_id, created_at DESC) INCLUDE (total_cents, status);Why the planner ignores your index
| Cause | Example | Fix |
|---|---|---|
| Function on the column | WHERE lower(email) = 'a@x.com' | Expression index: CREATE INDEX ON users (lower(email)) |
| Type mismatch | Comparing a text column to a number | Match types explicitly |
| Leading wildcard | LIKE '%term%' | pg_trgm + GIN index |
| Stale statistics | After a big data load | ANALYZE table_name; |
| Low selectivity | Filter matches 40% of rows | A sequential scan really is cheaper; consider a different design |
| Wrong column order | Index (b, a) for WHERE a = ? | Reorder or add an index |
For text search with wildcards:
CREATE EXTENSION IF NOT EXISTS pg_trgm;CREATE INDEX CONCURRENTLY idx_products_name_trgm ON products USING gin (name gin_trgm_ops);Step 4: Fix query shape, not just indexes
Select only what you need. SELECT * drags every column through memory and the network, and defeats index-only scans.
Replace OFFSET pagination. OFFSET 100000 forces PostgreSQL to produce and discard 100,000 rows. Use keyset pagination instead:
-- first pageSELECT id, created_at, titleFROM postsORDER BY created_at DESC, id DESCLIMIT 20;-- next page: pass the last row's (created_at, id)SELECT id, created_at, titleFROM postsWHERE (created_at, id) < ($1, $2)ORDER BY created_at DESC, id DESCLIMIT 20;Back it with CREATE INDEX ON posts (created_at DESC, id DESC).
Avoid N+1 queries. Loading 100 orders and then running one query per order for its items makes 101 round trips. Fetch the items in one query with WHERE order_id = ANY($1) or a join.
Aggregate in the database, not in application memory, and use EXISTS instead of COUNT(*) > 0 when you only need to know whether a row exists.
Step 5: Keep the database healthy
- Autovacuum removes dead row versions and keeps statistics and visibility maps fresh. Heavily updated tables may need tuned autovacuum settings.
ANALYZEafter bulk loads so the planner has accurate statistics.- Bloat (tables and indexes with lots of dead space) slows scans. Monitor it, and use
REINDEX CONCURRENTLYwhen an index is badly bloated. - Connection count: too many connections hurt performance. Use a pooler such as PgBouncer for applications that open many short-lived connections.
work_memaffects sorts and hash joins. Raise it carefully, since it applies per operation per connection.
Common mistakes
- Adding indexes without checking the plan, then wondering why nothing changed.
- Indexing every column, which slows writes and bloats storage.
- Testing on tiny development data, where a sequential scan always wins.
- Running
EXPLAINwithoutANALYZEand trusting estimates. - Forgetting
CONCURRENTLYand blocking writes on a busy table. - Fixing one query while an N+1 pattern makes thousands of them.
Testing and validation
For every change, record before and after:
- The
EXPLAIN (ANALYZE, BUFFERS)output on production-like data. - The query's
mean_exec_timeinpg_stat_statementsafter the change (reset stats withpg_stat_statements_reset()when comparing). - Write performance on the affected table, since new indexes add write cost.
Run the check against a copy of production data when you can, and test with realistic parameter values: plans depend on how common a value is.
Production considerations
Create indexes with CONCURRENTLY and during quieter periods, watch for failed concurrent builds (they can leave an INVALID index to drop), check replication lag if you use replicas, and keep a record of why each index exists so the next person knows when it is safe to remove.
Best practices
- Measure first:
pg_stat_statements, slow query log,EXPLAIN (ANALYZE, BUFFERS). - Match indexes to real query patterns: equality columns, then range or sort.
- Prefer keyset pagination for large result sets.
- Keep statistics fresh and autovacuum healthy.
- Re-check performance as data grows, because the best plan changes with table size.
Conclusion
PostgreSQL performance work is detective work with a small toolkit: find the costly statements, read the plan, change an index or the query shape, and measure again. The plan tells you what the database actually did, and once you can read it, slow queries stop being mysterious and become a short list of fixable patterns.
Frequently asked questions
+How do I find which PostgreSQL queries are slow?
Enable the pg_stat_statements extension and sort by total or mean execution time, and set log_min_duration_statement to log any query slower than a threshold. Start with the queries that consume the most total time, not just the slowest single run.
+What is the difference between EXPLAIN and EXPLAIN ANALYZE?
EXPLAIN shows the plan the planner chose with estimated costs. EXPLAIN ANALYZE actually runs the query and adds real timings and row counts. Because it executes the statement, wrap data-changing queries in a transaction you roll back.
+Is a sequential scan always bad?
No. For small tables, or when a query needs a large fraction of the rows, a sequential scan is often the fastest plan. It becomes a problem when it reads a big table to return a handful of rows.
+Why is PostgreSQL not using my index?
Common reasons: the index does not match the filter or sort (column order, a function applied to the column, a type mismatch), stale statistics, low selectivity so a scan is cheaper, or the table is small. Check the plan and run ANALYZE before assuming the planner is wrong.
+Do more indexes make everything faster?
No. Each index speeds up some reads but slows writes and uses disk and memory. Create indexes for real, measured query patterns and drop unused ones.
+How do I speed up LIKE '%term%' searches?
A plain B-tree index cannot help a leading wildcard. Use the pg_trgm extension with a GIN or GiST index, or use full-text search for natural-language matching.
+OFFSET pagination gets slower on later pages. What should I use?
Keyset (cursor) pagination. Filter by the last seen sort key instead of skipping rows with OFFSET, backed by an index on the sort columns.