Postgres Query Performance: Reading EXPLAIN ANALYZE and Fixing Slow Queries
Derar SattoufUpdated Backend & databases

Most application performance problems end at the database, and most database performance problems end at a handful of queries. The skill that separates teams who guess from teams who fix is the ability to read a query plan.
Find the expensive queries before you try to fix anything: use pg_stat_statements to rank queries by total time, not by gut feeling. Then measure with EXPLAIN (ANALYZE, BUFFERS) and compare estimated rows against actual rows. Big gaps mean bad statistics or a misunderstood query. A Seq Scan isn't always bad. It's bad when it reads many rows to return few.
The usual fix is an index, a rewrite, a statistics change, or sometimes a schema change. Index for your WHERE, JOIN, and ORDER BY columns, in the right order, and consider partial and covering indexes. On large tables, replace OFFSET pagination with keyset pagination. And keep ANALYZE and autovacuum healthy, because stale statistics cause most "the planner is dumb" incidents.
Step zero: find the queries worth fixing
Enable the extension (it must be in shared_preload_libraries):
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT
round(total_exec_time::numeric, 0) AS total_ms,
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 1) AS pct,
rows,
left(query, 120) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 15;Rank by total time (frequency times duration). A 5 ms query called 50 million times costs more than a 2-second report run twice a day. Also check:
mean_exec_timeandstddev_exec_timefor latency-sensitive endpoints.shared_blks_read(disk reads) vsshared_blks_hit(cache hits).
Turn on slow query logging as a safety net:
ALTER SYSTEM SET log_min_duration_statement = '250ms';
ALTER SYSTEM SET auto_explain.log_min_duration = '500ms'; -- requires auto_explain loaded
SELECT pg_reload_conf();Reading a plan
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT o.id, o.total, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending'
AND o.created_at > now() - interval '7 days'
ORDER BY o.created_at DESC
LIMIT 50;Sample output (trimmed):
Limit (cost=18204.5..18204.6 rows=50 width=48) (actual time=412.8..412.9 rows=50 loops=1)
Buffers: shared hit=2210 read=48120
-> Sort (cost=18204.5..18390.2 rows=74280 width=48) (actual time=412.8..412.8 rows=50 loops=1)
Sort Key: o.created_at DESC
Sort Method: top-N heapsort Memory: 32kB
-> Hash Join (cost=2891.0..16310.4 rows=74280 width=48) (actual time=35.1..390.2 rows=81342 loops=1)
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o (cost=0.00..13212.0 rows=74280 width=40) (actual time=0.02..301.4 rows=81342 loops=1)
Filter: ((status = 'pending') AND (created_at > (now() - '7 days'::interval)))
Rows Removed by Filter: 4918658
-> Hash (cost=1641.0..1641.0 rows=100000 width=24) (actual time=34.9..34.9 rows=100000 loops=1)
Planning Time: 0.6 ms
Execution Time: 413.1 msHow to read it
- Read from the innermost, most-indented node outward. Data flows from leaves to the root.
- Each node shows
cost(planner estimate, arbitrary units), and withANALYZE,actual time,rows, andloops. Multiply actual time and rows by loops for the true per-node total. - Estimated rows vs actual rows: here they match well (74,280 vs 81,342), so statistics are fine. A mismatch of 10x or more is a red flag.
Rows Removed by Filter: 4,918,658: the scan read five million rows to keep 81 thousand. That is the problem.Buffers: shared read=48120: tens of thousands of pages came from disk or the OS cache rather than shared buffers.
The fix is an index that lets Postgres jump straight to pending recent orders.
Plan node cheat sheet
| Node | Meaning | Worry when |
|---|---|---|
| Seq Scan | Reads the whole table | Many rows removed by filter |
| Index Scan | Walks the index, fetches heap rows | Many random heap fetches for low selectivity |
| Index Only Scan | Answers from the index | Heap Fetches is high (vacuum the table) |
| Bitmap Index/Heap Scan | Collects row locations, then reads pages in order | Lossy blocks, memory pressure |
| Nested Loop | For each outer row, probe inner | Large outer row count and slow inner node |
| Hash Join | Builds a hash of one side | Batches greater than 1 (spilled to disk) |
| Merge Join | Merges two sorted inputs | Expensive sorts feeding it |
| Sort / Incremental Sort | Orders rows | external merge on disk |
| Aggregate / HashAggregate | Group and sum | Disk usage with many groups |
| Gather / Parallel nodes | Parallel workers | Fewer workers launched than planned |
Settings that make plans more informative
SET track_io_timing = on; -- shows I/O time per node (small overhead; check your version/cluster defaults)
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, WAL, FORMAT TEXT) SELECT ...;
-- EXPLAIN without ANALYZE never runs the query. EXPLAIN ANALYZE DOES run it:
-- wrap writes in a transaction you roll back.
BEGIN;
EXPLAIN (ANALYZE, BUFFERS) UPDATE orders SET status = 'x' WHERE id < 1000;
ROLLBACK;Version notes: recent Postgres releases keep improving this area. Postgres 18 (released in September 2025) reports buffer usage in EXPLAIN ANALYZE without asking for it, adds B-tree skip scans (so an index on (a, b) can sometimes help a query that only filters on b), and introduces asynchronous I/O options for reads. Confirm what your version and your managed provider support in the release notes before relying on them. The advice here still applies on older versions; the main difference is spelling out BUFFERS.
Hands-on lab: reproduce the problem locally
-- 1. Build a table large enough to matter
CREATE TABLE lab_orders AS
SELECT g AS id,
(random() * 100000)::int AS customer_id,
(ARRAY['pending','paid','shipped','cancelled'])[1 + (random()*3)::int] AS status,
now() - (random() * interval '365 days') AS created_at,
(random() * 500)::numeric(8,2) AS total
FROM generate_series(1, 3000000) g;
ANALYZE lab_orders;
-- 2. Measure without an index
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total FROM lab_orders
WHERE status = 'pending' AND created_at > now() - interval '7 days'
ORDER BY created_at DESC LIMIT 50;
-- 3. Add the index and measure again
CREATE INDEX idx_lab_status_created ON lab_orders (status, created_at DESC);
ANALYZE lab_orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total FROM lab_orders
WHERE status = 'pending' AND created_at > now() - interval '7 days'
ORDER BY created_at DESC LIMIT 50;
-- 4. Clean up
DROP TABLE lab_orders;Expect the second plan to switch from a sequential scan and sort to an index scan that returns already-ordered rows with the Limit stopping early. Exact timings depend on your machine; compare plans and buffer counts, not absolute milliseconds.
Index strategy
Basic rule: equality columns first, then range, then sort
For WHERE status = ? AND created_at > ? ORDER BY created_at DESC:
CREATE INDEX CONCURRENTLY idx_orders_status_created
ON orders (status, created_at DESC);Column order matters. A B-tree on (status, created_at) serves queries filtering on status alone or status plus created_at, but not created_at alone efficiently.
Partial indexes: index only what you query
If only a small fraction of rows are pending, index just those:
CREATE INDEX CONCURRENTLY idx_orders_pending_created
ON orders (created_at DESC)
WHERE status = 'pending';Smaller, faster to maintain, and fits in memory. The query's WHERE must imply the index predicate for the planner to use it.
Covering indexes: avoid heap fetches
CREATE INDEX CONCURRENTLY idx_orders_cust_created_cov
ON orders (customer_id, created_at DESC)
INCLUDE (total, status);With INCLUDE, the query can be answered via an Index Only Scan (provided the visibility map is current via vacuum), skipping table lookups.
Other index types worth knowing
| Type | Use for |
|---|---|
| B-tree | Equality, ranges, sorting (the default) |
| GIN | jsonb containment, arrays, full-text search |
| GiST | Geometric, range types, exclusion constraints |
| BRIN | Huge append-only tables correlated with physical order (timestamps) |
| Hash | Rarely better than B-tree for equality; niche |
-- JSONB containment queries
CREATE INDEX CONCURRENTLY idx_events_payload ON events USING gin (payload jsonb_path_ops);
-- Query: WHERE payload @> '{"type":"signup"}'
-- Case-insensitive lookup
CREATE INDEX CONCURRENTLY idx_users_email_lower ON users (lower(email));
-- Query must use lower(email) = lower($1)Indexes are not free
Each index slows writes and consumes space. Find unused ones and drop them:
SELECT schemaname, relname, indexrelname, idx_scan, pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0 AND indexrelname NOT LIKE '%_pkey'
ORDER BY pg_relation_size(indexrelid) DESC;Always create indexes on live tables with CREATE INDEX CONCURRENTLY to avoid blocking writes (it cannot run inside a transaction block).
Plan patterns and what they mean
Seq Scan on a big table with a selective filter
Missing or unusable index. Also check for functions on indexed columns (WHERE date(created_at) = ... defeats an index on created_at; rewrite as a range) and implicit casts (comparing a text column to an integer parameter).
-- Bad: cannot use index on created_at
WHERE date(created_at) = '2026-11-01'
-- Good: sargable range
WHERE created_at >= '2026-11-01' AND created_at < '2026-11-02'Nested Loop with huge loops
A nested loop running an inner index scan 200,000 times can be fine (each is a microsecond) or terrible (each is a milliseconds). Look at inner actual time * loops. If estimates for the outer side are far too low, the planner chose a nested loop for what is really a big join; fix statistics.
Sort spilling to disk
Sort Method: external merge Disk: 84000kB means work_mem was too small. Either add an index that provides pre-sorted output, reduce the rows being sorted, or raise work_mem for that session or role (not globally; it is allocated per sort/hash node per connection).
SET LOCAL work_mem = '128MB'; -- inside a transaction for a heavy reportBitmap Heap Scan with lossy blocks
Fine for medium selectivity. Heap Blocks: lossy indicates work_mem pressure.
Row estimate way off
rows=1 estimated, rows=250000 actual. Causes: stale stats, correlated columns, skewed data. Fixes below.
Fixing bad estimates
-- Refresh statistics
ANALYZE orders;
-- Skewed column: collect more detail (default target is 100)
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000;
ANALYZE orders;
-- Correlated columns (e.g. country and city): extended statistics
CREATE STATISTICS orders_cust_status (dependencies, ndistinct)
ON customer_id, status FROM orders;
ANALYZE orders;Check that autovacuum keeps up on hot tables:
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum, last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC LIMIT 10;For large, frequently updated tables, lower the per-table thresholds:
ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.02, autovacuum_analyze_scale_factor = 0.01);Pagination: stop using big OFFSETs
-- Slow at depth: must read and discard 100,000 rows
SELECT * FROM events ORDER BY created_at DESC, id DESC OFFSET 100000 LIMIT 50;Use keyset (seek) pagination: remember the last row's sort key and continue from there.
CREATE INDEX CONCURRENTLY idx_events_created_id ON events (created_at DESC, id DESC);
-- First page
SELECT id, created_at, title FROM events
ORDER BY created_at DESC, id DESC
LIMIT 50;
-- Next page: pass last row's values
SELECT id, created_at, title FROM events
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 50;Cost stays constant no matter how deep the user pages. Include a unique tiebreaker (id) so rows with identical timestamps are neither skipped nor repeated.
The N+1 problem and chatty code
The most common application-level slowness is not a slow query but 500 fast ones.
// N+1: one query for posts, then one per post
const posts = await db.query("SELECT * FROM posts LIMIT 50");
for (const p of posts) {
p.author = await db.query("SELECT * FROM users WHERE id = $1", [p.author_id]);
}
// Fix 1: JOIN
const rows = await db.query(`
SELECT p.*, u.name AS author_name
FROM posts p JOIN users u ON u.id = p.author_id
LIMIT 50`);
// Fix 2: batch with ANY
const users = await db.query("SELECT * FROM users WHERE id = ANY($1)", [posts.map(p => p.author_id)]);Detect it by looking at calls in pg_stat_statements: a trivial query with an enormous call count per request is the signature. ORMs (Prisma include, Django select_related / prefetch_related, Rails includes) have eager-loading features; use them deliberately.
Other high-impact fixes
SELECT *: fetching wide rows (including TOASTedjsonbortext) blocks index-only scans and wastes bandwidth. Select only what you need.COUNT(*)on big tables: it requires scanning. Use approximate counts (reltuplesfrompg_class) for UI totals, or maintain counters.IN (subquery)vsEXISTS:EXISTSoften plans better for existence checks. Test both.- CTEs: since Postgres 12, simple CTEs are inlined; use
MATERIALIZED/NOT MATERIALIZEDto control it. - Connection pooling: hundreds of active backends hurt throughput. Use PgBouncer (transaction mode) and size pools carefully.
- Partitioning for very large time-series tables, to prune scans and make retention a
DROP PARTITION.
-- Compare two formulations quickly
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.id FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.status = 'pending');A repeatable workflow
- Identify the top queries by
total_exec_timeinpg_stat_statements. - Reproduce with realistic parameters on production-like data (planner choices depend on data volume and distribution; an empty dev database lies).
- Run
EXPLAIN (ANALYZE, BUFFERS). Note the node with the largest actual time, row-estimate gaps, andRows Removed by Filter. - Apply the smallest fix: index, rewrite, statistics, config.
- Re-run the plan; confirm improvement in both time and buffers.
- Create indexes
CONCURRENTLY; deploy; watchpg_stat_statementsafter resetting or comparing deltas. - Add a regression guard: a test with a query-count assertion for N+1, or a dashboard alert on p95 query time.
Tools that help: pev2 or explain.dalibo.com to visualize plans, pgBadger for log analysis, pg_stat_kcache, and hypopg for testing hypothetical indexes without building them.
-- hypopg: test an index without creating it
CREATE EXTENSION hypopg;
SELECT * FROM hypopg_create_index('CREATE INDEX ON orders (status, created_at DESC)');
EXPLAIN SELECT ... ; -- the planner will consider the hypothetical indexWhen the query is fine but the database is slow
Not every slowdown is a bad plan.
Locks and long transactions
-- Who is waiting on whom?
SELECT a.pid, a.state, a.wait_event_type, a.wait_event, now() - a.xact_start AS xact_age, left(a.query, 80) AS query
FROM pg_stat_activity a
WHERE a.state <> 'idle'
ORDER BY a.xact_start NULLS LAST;
SELECT blocked.pid AS blocked_pid, blocking.pid AS blocking_pid, left(blocking.query, 80) AS blocking_query
FROM pg_stat_activity blocked
JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid) ON true
JOIN pg_stat_activity blocking ON blocking.pid = b.pid;Long-open transactions also block vacuum from removing dead rows, which bloats tables and indexes. Set idle_in_transaction_session_timeout and statement_timeout for application roles, and keep transactions short. Schema changes need extra care; see zero-downtime Postgres migrations.
Bloat
-- Rebuild a bloated index without blocking writes
REINDEX INDEX CONCURRENTLY idx_orders_status_created;Heavy update patterns create dead tuples; tune autovacuum per table (see the section on fixing bad estimates) before reaching for VACUUM FULL, which takes an exclusive lock.
Planner cost settings
On SSD or NVMe storage the old default random_page_cost = 4 can make the planner avoid indexes it should use; many teams set a value closer to 1.1 to 2. Change it on a test system, compare plans on your top queries, and roll out deliberately. Also check effective_cache_size (a hint about total cache, roughly the size of shared buffers plus OS cache) and shared_buffers.
Prepared statements and generic plans
Drivers and ORMs may use prepared statements. After several executions Postgres can switch to a generic plan that ignores parameter values, which is bad for skewed data. If one parameter value is slow and others fast, test with SET plan_cache_mode = force_custom_plan and compare.
JIT
For short OLTP queries JIT compilation can add overhead rather than help. If EXPLAIN shows large JIT timings on quick queries, consider raising jit_above_cost or turning JIT off for that workload.
Connections and memory
Total memory risk is roughly max_connections times work_mem times the number of sort and hash nodes per query. Use a pooler and keep work_mem modest globally; raise it per session for known heavy reports.
Where this usually goes wrong
- Running
EXPLAINwithoutANALYZEand trusting cost numbers as time. - Testing on a tiny dev database and shipping a plan that falls apart at 100 million rows.
- Adding an index for every slow query without checking write cost or existing overlapping indexes.
- Creating indexes without
CONCURRENTLYon a busy table. - Wrapping an indexed column in a function (
lower(email),date(created_at)) without a matching expression index or a range rewrite. - Comparing different types (a
bigintcolumn with anumericparameter,uuidwithtext) which can force casts and skip indexes. - Setting
work_memvery high globally. - Reading only the root node of the plan instead of the node with the largest exclusive time.
- Ignoring
loopswhen computing the real cost of a node.
Troubleshooting table
| Symptom | First check | Likely fix |
|---|---|---|
| Query fast alone, slow in production | Locks, cache state, parameter values | Check pg_stat_activity, test with real parameters |
| Index exists but is not used | Sargability, types, selectivity, stale stats | Rewrite predicate, ANALYZE, check enable_* only for diagnosis |
| Estimates wrong by 10x or more | n_distinct, correlation, stale stats | ANALYZE, raise statistics target, extended statistics |
| Sort or hash spills to disk | external merge or Batches in the plan | Add an ordering index, reduce rows, raise work_mem per session |
| Latency spikes at regular intervals | Checkpoints, autovacuum, cron jobs | Inspect logs, pg_stat_bgwriter and pg_stat_io |
| Writes got slower after adding indexes | Too many indexes on hot tables | Remove unused indexes, partial indexes |
Questions that come up
Should I disable enable_seqscan? Only as a temporary diagnostic in one session to see what the index plan would cost. Never in production configuration.
How do I get the plan of a slow query in production? Use auto_explain to log plans for statements above a threshold, and copy the query with real parameters into EXPLAIN (ANALYZE, BUFFERS) on a replica or restored copy.
How big should shared_buffers be? A common starting point is about a quarter of RAM on a dedicated server, then tune with measurements; managed services often set it for you.
ORM generates terrible SQL, what now? Log the SQL, fix eager loading, add the missing index, and if needed drop to raw SQL for that query. See the ORM sections in Django performance optimization.
What about vector or full-text indexes? The same method applies; for pgvector specifics see Postgres for AI apps.
Sources and docs
- PostgreSQL: Using EXPLAIN
- PostgreSQL: pg_stat_statements
- PostgreSQL: Index types
- PostgreSQL: Routine vacuuming
- PostgreSQL: auto_explain
- Use The Index, Luke
- PEV2 plan visualizer
- Related on this site: Redis and Valkey caching strategies, SQLite in production, API rate limiting, idempotency and pagination