Friday evening, and production is barely responding. Latency is climbing, users are hammering F5 on the orders page, and the first instinct is familiar: 'Let's throw an index on orders, that'll fix it.' The index goes live, writes slow down, disk space shrinks, and the lag doesn't budge.
Guessing rarely works here. Most web app slowdowns do hit the database, and usually only a handful of queries are to blame. Spotting them by eye is nearly impossible: the loudest suspect is often harmless, while the real culprit hides among 'fast' queries. To fix a database without flying blind, you need a simple loop: measure actual resource usage, read the execution plan, and make the smallest targeted fix.
Step Zero: Why You Can't Guess and Where to Find Real Database Hogs
The first trap is chasing the query with the highest average duration. Compare two queries in the same cluster. The first is a heavy two-second report run twice a day. The second is a tiny 5-millisecond query called 50 million times. Multiply duration by frequency, and the 'fast' query burns orders of magnitude more CPU and disk I/O than the two-second report.
That's why every investigation starts with total execution time — the total_exec_time column in pg_stat_statements. It collects stats on normalized SQL queries (replacing literals with parameters), tracking call counts, mean time, variance, and buffer activity.
First, add the extension to shared_preload_libraries in postgresql.conf and restart PostgreSQL — it can't be loaded on the fly. Then enable it in your database and pull the top 15 costliest queries:
-- Enable the extension in the database (after shared_preload_libraries)
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
-- Top 15 queries by total execution time
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;
The output immediately shows each query's share of total load (pct). If the first one eats 45% of database time and the tenth takes less than 1%, you know right where to look.
Beyond total_exec_time, check mean_exec_time and stddev_exec_time on user-facing endpoints. High variance exposes unstable queries that fly when cached and stall on disk or locks. Columns shared_blks_read and shared_blks_hit show how often a query misses PostgreSQL's cache, while a huge calls count on a simple SELECT ... WHERE id = $1 almost always points to an N+1 loop in app code.
If you need to separate real physical disk reads from OS page-cache hits, add pg_stat_kcache. It reads OS metrics via getrusage and also reports per-query CPU usage.
Also enable a safety net in your logs so rare heavy spikes don't vanish:
-- Log queries slower than 250 ms
ALTER SYSTEM SET log_min_duration_statement = '250ms';
-- Log execution plans for slow queries (requires auto_explain in preload)
ALTER SYSTEM SET auto_explain.log_min_duration = '500ms';
-- Apply without restarting the server
SELECT pg_reload_conf();
You also add auto_explain to shared_preload_libraries. In return, if a query stalls for three seconds at 3 a.m., its full plan with real parameters will already be waiting in the log.
Anatomy of EXPLAIN (ANALYZE, BUFFERS): Reading the Tree Bottom-Up
Suppose the top list flags a query that fetches the 50 latest pending orders from the last 7 days and joins customer emails from customers. Run it through EXPLAIN with ANALYZE, BUFFERS, and VERBOSE:
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;
On a multi-million-row table, PostgreSQL produces a plan like this, showing right away where nearly half a second goes:
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 ms
Reading this output is easiest with five rules.
First: read bottom-up, from the deepest nested nodes toward the root. Data flows in that exact order: leaf nodes read tables, middle nodes join and sort rows, and the top Limit slices off 50 rows.
Second: cost is in planner units, not milliseconds. Real timings appear with ANALYZE inside actual time (time to first row and total completion). Always check loops: if a node runs in a loop, its actual time and row count are multiplied by loops.
Third: compare estimated rows with actual rows. In Seq Scan on orders, the planner expected 74,280 rows and got 81,342 — the stats are healthy. A red flag goes up when the estimate is off by 10x or more.
Fourth: Rows Removed by Filter: 4918658 points straight to the bottleneck. To return 50 orders, the database scanned five million rows, threw almost all of them away, pushed the remaining 81,000 through a Hash Join, sorted them, and only then took the top 50.
Fifth: Buffers shows how many 8 KB pages came from PostgreSQL's cache (shared hit) versus the OS cache or disk (shared read).
Where the Query Fetched Data Pages During Seq Scan on orders
The chart shows the scale of the miss: nearly all data bypassed PostgreSQL's internal cache. On a warm second run, milliseconds may drop, but the number of pages read stays huge and keeps evicting hot data needed by other queries.
Here is a quick cheat sheet for ten core plan nodes and the warning signs to watch.
| Plan Node | What PostgreSQL Does | Warning Sign |
|---|---|---|
Seq Scan | Reads the entire table page by page | Huge Rows Removed by Filter for a handful of rows |
Index Scan | Looks up pointers in the index, then fetches rows from the heap | Thousands of random table reads with weak filtering |
Index Only Scan | Returns columns straight from the index without touching the table | High Heap Fetches — stale visibility map, needs VACUUM |
Bitmap Index / Heap Scan | Builds a page bitmap, then reads pages in order | Lossy blocks appear — work_mem is too small |
Nested Loop | Scans the inner node for each outer row | Many outer rows plus a slow inner node (time × loops) |
Hash Join | Builds a hash table on one side and probes with the other | Batches > 1 — hash table spilled to disk |
Merge Join | Merges two pre-sorted streams | Expensive Sort nodes below eat up the gain |
Sort / Incremental Sort | Sorts rows by key | Sort Method: external merge Disk — spilled to disk |
Aggregate / HashAggregate | Groups rows and computes aggregates | Disk spill when group count is high |
Gather / Parallel nodes | Launches parallel worker processes | Fewer workers launched than planned |
When a plan stretches to a hundred lines, paste it into the open-source visualizer PEV2 (dalibo/pev2). It draws an interactive tree highlighting the slowest nodes, estimation errors, and buffer hits. If your plan contains real user emails or secrets, don't paste it into a public web app — run PEV2 locally.
PostgreSQL plan visualizer PEV2 interface showing the node tree, execution time, and buffers (Source: official dalibo/pev2 repository)
For write queries, follow one strict safety rule.
Plain EXPLAIN only builds a plan. Adding ANALYZE runs the statement for real: if you run it on an UPDATE or DELETE without a rollback, you will modify production data.
Always wrap write queries in BEGIN ... ROLLBACK, and enable track_io_timing in your session when you want per-node I/O timings:
-- Enable per-node I/O timing for the current session
SET track_io_timing = on;
-- Extended output with settings and WAL stats
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, WAL, FORMAT TEXT)
SELECT ...;
-- Safe write-query test with rollback
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
UPDATE orders SET status = 'x' WHERE id < 1000;
ROLLBACK;
After ROLLBACK, the table remains untouched, and you have accurate timings and buffer counters in hand.
PostgreSQL 18, released on September 25, 2025, brought welcome improvements (by December 2026, the current official docs already point to PostgreSQL 19). First, EXPLAIN ANALYZE in 18+ turns on BUFFERS automatically, reports index lookups, and adds richer CPU and WAL details in VERBOSE mode. Second, B-tree skip scan arrived: a composite index (a, b) can now help even without a filter on a, as long as b is selective and a has few distinct values. Third, asynchronous I/O (io_method with worker and io_uring, io_combine_limit, and the pg_aios view) speeds up Seq Scan, Bitmap Heap Scan, and VACUUM. Check your cluster version before relying on these features.
A 3-Million-Row Local Lab: Watching Seq Scan Flip to Index Scan
Testing queries against a local table with a thousand rows is a sure path to a production incident. The planner picks a path based on table size and data distribution: on 1,000 rows, reading the whole table is faster, so both good and broken queries finish in half a millisecond.
In half a minute, you can build a realistic lab_orders table with 3 million rows and watch the plan change before and after adding your first index:
-- 1. Generate 3M orders
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 (Seq Scan + Sort)
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 a composite 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 the lab table
DROP TABLE lab_orders;
The first run shows a familiar Seq Scan discarding millions of rows and sorting the rest. The second run uses an Index Scan on idx_lab_status_created: rows are already grouped by status and sorted newest-first, so Limit stops after reading just 50 entries. Compare the plan structure and Buffers counts rather than raw laptop milliseconds, which jump around with the OS cache.
Indexing Without Hurting Writes: Column Order, Partial, Covering, and Cleanup
After seeing your first 100x speedup, it's tempting to index everything. Hold back: every index must be updated on every INSERT, DELETE, and many UPDATE statements. A dozen extra indexes on a hot table will quickly bog down writes and eat RAM.
For a composite B-tree index, follow the standard column order rule: equality (=) first, then range (>, <, BETWEEN), then sort (ORDER BY). An index on (status, created_at DESC) serves filters on status and status + created_at while eliminating the sort step. For a filter on created_at alone, it's usually useless (aside from narrow B-tree skip scan cases in PG 18+ when status has low cardinality).
Isometric cutaway of PostgreSQL indexing strategies: B-tree column order, compact partial index, and covering index with INCLUDE avoiding heap fetches.
On live tables, always build indexes with CONCURRENTLY (see the CREATE INDEX docs). A plain CREATE INDEX blocks writes until it finishes. CONCURRENTLY has three key caveats: it cannot run inside a BEGIN ... COMMIT transaction; it takes longer because it makes two passes over the table (track progress in pg_stat_progress_create_index); and if it fails (from a deadlock or uniqueness violation), it leaves behind an invalid index (indisvalid = false) that the planner ignores while writes still update it. Drop that broken index with DROP INDEX CONCURRENTLY and rebuild it.
-- Composite index without blocking writes
CREATE INDEX CONCURRENTLY idx_orders_status_created
ON orders (status, created_at DESC);
-- Partial index: only pending orders
CREATE INDEX CONCURRENTLY idx_orders_pending_created
ON orders (created_at DESC)
WHERE status = 'pending';
-- Covering index: Index Only Scan without heap access
CREATE INDEX CONCURRENTLY idx_orders_cust_created_cov
ON orders (customer_id, created_at DESC)
INCLUDE (total, status);
A partial index shines when 98% of a table holds closed orders and your app constantly queries pending ones: the index stays tiny and fits in RAM, as long as the query's WHERE clause logically implies the index predicate. A covering index with INCLUDE stores extra columns in leaf pages, enabling an Index Only Scan without touching the table heap. The only requirement is an up-to-date visibility map maintained by VACUUM; if Heap Fetches climbs in your plan, VACUUM is falling behind.
PostgreSQL offers five main index types for different workloads.
| Index Type | Best Suited For | When to Use |
|---|---|---|
B-tree | Equality, ranges, sorting | Default choice for most columns (numbers, dates, strings, UUIDs) |
GIN | jsonb containment (@>), arrays, full-text search | Filtering on JSONB keys and array elements |
GiST | Geometry, date ranges, EXCLUDE constraints | Maps, overlapping intervals, conflict-free bookings |
BRIN | Huge append-only tables (logs, events) | Hundreds of millions of rows physically ordered by time |
Hash | Strict equality (=) only | Niche use cases; rarely beats modern B-tree |
For jsonb, the jsonb_path_ops operator class is smaller and faster than default GIN. For case-insensitive email lookups, use an expression index — just make sure the query writes the exact same lower(email) = lower($1) expression:
-- JSONB containment: WHERE payload @> '{"type":"signup"}'
CREATE INDEX CONCURRENTLY idx_events_payload
ON events USING gin (payload jsonb_path_ops);
-- Expression index
CREATE INDEX CONCURRENTLY idx_users_email_lower
ON users (lower(email));
Both speed up frequent lookups, and every couple of months you should check pg_stat_user_indexes for dead indexes:
-- Large indexes that have never been scanned
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;
Before dropping an index, verify it doesn't back a UNIQUE constraint, that stats cover a full business cycle (including monthly reports), and that read replicas don't rely on it.
When the Planner Misbehaves: Functions in WHERE, Disk Spills, and Extended Stats
Complaints like 'the index exists, why isn't Postgres using it?' almost always come down to three things: a broken WHERE clause, stale stats, or hidden correlation between columns.
The moment an indexed column is wrapped in a function like date(created_at) or compared against a mismatched type (bigint vs numeric, uuid vs text), the condition stops being sargable (index-searchable). A plain B-tree goes blind. Rewrite the filter as an explicit range:
-- Bad: index on created_at is ignored
WHERE date(created_at) = '2026-11-01'
-- Good: sargable range uses the index
WHERE created_at >= '2026-11-01'
AND created_at < '2026-11-02'
You get the exact same 24-hour slice, and PostgreSQL happily uses the index.
Another common pitfall is a Nested Loop with huge iteration counts. A loop isn't bad by itself: 200,000 one-microsecond iterations finish in 0.2 seconds, while one-millisecond iterations take three minutes. If the plan estimates rows=1 when actual rows is 250000, stale stats tricked the planner into picking the loop.
The third red flag is spilling to disk: Sort Method: external merge Disk: 84000kB, Batches > 1 on a Hash Join, or lossy blocks on a Bitmap Heap Scan. That node ran out of work_mem. This setting caps memory per sort or hash node inside a query. Peak memory can reach max_connections × work_mem × number of Sort/Hash nodes, so raising work_mem globally risks an OOM crash. Instead, add an index that provides the sort order, filter rows earlier, or raise the limit for a single transaction:
-- Temporarily raise work_mem for a heavy report
BEGIN;
SET LOCAL work_mem = '128MB';
-- run your query here
COMMIT;
Right after COMMIT, the limit drops back to the safe system default.
If row estimates are off by orders of magnitude, fix your statistics. By default, the planner assumes columns are independent (as if country and city had no relation). On correlated pairs like customer_id and status, that causes wild misses. Run ANALYZE, raise the sample target with SET STATISTICS (default is 100), and add extended statistics via CREATE STATISTICS using dependencies, ndistinct, and mcv (most-common value lists):
-- 1. Refresh statistics
ANALYZE orders;
-- 2. Increase detail for a skewed column
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000;
ANALYZE orders;
-- 3. Teach the planner about column correlation
CREATE STATISTICS orders_cust_status (dependencies, ndistinct, mcv)
ON customer_id, status FROM orders;
ANALYZE orders;
-- 4. Check whether 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;
-- 5. Lower autovacuum thresholds for a large table
ALTER TABLE orders SET (
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_analyze_scale_factor = 0.01
);
On tables with tens of millions of rows, the default 10–20% autovacuum threshold triggers too late and lets stats go stale. To test a hypothesis once in a local session, you can run SET enable_seqscan = off; to see how the planner prices an index plan — just never leave that setting enabled in production.
Where Indexes Won't Save You: Keyset Pagination, N+1, and SQL Habits
Even with perfect indexes, application code can still bring a database to its knees by how it fetches data.
The first culprit is deep OFFSET. When someone opens a faraway page with LIMIT 50 OFFSET 100000, PostgreSQL must read 100,050 rows and discard the first 100,000. The deeper the page, the worse it gets. Worse, if new orders arrive at the top of the feed, rows shift and duplicates appear on the next page.
The fix is keyset (seek) pagination: instead of a page number, pass a bookmark from the last displayed row. Pair created_at with a unique tie-breaker like id so rows sharing the same timestamp never duplicate or disappear between pages:
-- Index matching the feed sort order
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 starting after the last row of the previous page
SELECT id, created_at, title
FROM events
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 50;
This query costs the same at any depth. Try it in the simulator below: insert a couple of new orders on page 1, move to page 2, then jump to page 200 — the gap between OFFSET and keyset shows up right away.
Pagination Simulator: OFFSET vs Keyset When Inserting New Rows
When jumping deep into the feed, OFFSET scans and discards hundreds of rows, while fresh inserts between clicks cause duplicates. Keyset reads only one page and stays consistent during inserts. Its only limit is that you can't jump straight to page 47 by number, but for feeds and APIs it is by far the safest choice.
The second app-level enemy is the N+1 problem. In pg_stat_statements, it hides as a harmless fast query with a massive calls count: one query for 50 posts triggers 50 extra queries for their authors. Fix it with a JOIN or a batched WHERE id = ANY($1):
// Bad (N+1): 1 query for posts + 50 queries for authors
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: single query with 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: single batch using ANY($1)
const users = await db.query(
"SELECT * FROM users WHERE id = ANY($1)",
[posts.map((p) => p.author_id)]
);
In ORMs, enable eager loading deliberately (include in Prisma, select_related / prefetch_related in Django, includes in Rails), and assert SQL query counts in tests on hot endpoints.
A few other costly SQL habits take minutes to fix. Don't scatter SELECT * everywhere — heavy jsonb and text columns pulled from TOAST clog the network and break Index Only Scan. Don't run exact COUNT(*) across tens of millions of rows for a UI badge — reltuples in pg_class or a dedicated counter is plenty for an estimate. When checking related rows, compare IN (subquery) against EXISTS:
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'
);
With EXISTS, the database stops scanning a customer's orders on the first match, which often yields a better plan. Also remember that since PostgreSQL 12, single-use CTEs inline automatically (override manually with MATERIALIZED / NOT MATERIALIZED). If your app holds hundreds of connections, put PgBouncer in transaction mode in front of the database. For huge event tables, partition by time so the planner prunes old partitions and cleanup becomes an instant DROP TABLE.
Pre-Production Checks: Hypothetical Indexes, Locks, Bloat, and Tuning
Building an index 'just to test' on a 200 GB table is slow and risky. The HypoPG (hypopg) extension solves this in a millisecond: it creates a virtual index in session memory with zero disk writes or locks, and plain EXPLAIN (without ANALYZE) shows whether the planner picks it:
Miniature diorama of pre-production PostgreSQL diagnostics: HypoPG virtual index, finding idle in transaction locks, and cleaning bloated indexes with REINDEX CONCURRENTLY.
-- Create a virtual index with no disk writes
CREATE EXTENSION hypopg;
SELECT *
FROM hypopg_create_index(
'CREATE INDEX ON orders (status, created_at DESC)'
);
-- Check the planner response (use EXPLAIN without ANALYZE)
EXPLAIN
SELECT id, total
FROM orders
WHERE status = 'pending'
AND created_at > now() - interval '7 days'
ORDER BY created_at DESC
LIMIT 50;
If EXPLAIN picks the virtual index and slashes the cost, you can safely run CREATE INDEX CONCURRENTLY. If it ignores the index, you just saved yourself half an hour.
Not every slowdown comes from the query plan, though. When everything flies locally and stalls in production, look for locks, stuck transactions, or bloat (table and index files swelling with dead tuples after heavy UPDATE/DELETE traffic that autovacuum can't clean because of a long-running transaction). Catch long transactions and lock chains using pg_stat_activity and pg_blocking_pids:
-- 1. Active and stuck transactions by age
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;
-- 2. Who is blocking whom right now
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;
The sneakiest enemy of autovacuum is forgotten idle in transaction sessions. Guard against them with idle_in_transaction_session_timeout and statement_timeout on application roles. For an already bloated index, rebuild it without blocking writes using REINDEX INDEX CONCURRENTLY idx_orders_status_created; rather than resorting to VACUUM FULL and its exclusive lock.
If queries and locks look clean yet oddities remain, check four config settings. The default random_page_cost = 4 was tuned for old HDDs and scares the planner away from index scans; on SSDs and NVMe, teams often lower it to 1.1–2.0 after benchmarking key queries, alongside checking effective_cache_size (roughly shared_buffers plus OS cache) and shared_buffers (typically starting at 25% of RAM on a dedicated server).
Prepared statements have their own quirk: after a few runs, PostgreSQL switches to a generic plan, which can suddenly stall on skewed parameter values — test this with SET plan_cache_mode = force_custom_plan. On short OLTP queries, JIT compilation can sometimes add overhead: if JIT timings show up in EXPLAIN, raise jit_above_cost or turn JIT off for that workload. Finally, periodic latency spikes often trace back to checkpoints, autovacuum, or cron jobs — spot them with pg_stat_bgwriter, pg_stat_io, and pgBadger, which builds visual HTML reports from PostgreSQL and PgBouncer logs.
Keep these six common symptoms and first checks handy in one table.
| Symptom | Likely Cause | What to Check First |
|---|---|---|
| Fast alone, slow in prod | Locks, cache, different parameters | pg_stat_activity, test with realistic params and volume |
| Index exists, not used | Sargability, types, selectivity, stale stats | Rewrite WHERE, ANALYZE, one-off enable_seqscan check |
| Estimates off by 10x+ | Skew, correlated columns, stale stats | ANALYZE, SET STATISTICS 1000, CREATE STATISTICS |
| Sort or hash spills to disk | external merge / Batches > 1 (low work_mem) | Ordered index, fewer rows, SET LOCAL work_mem |
| Periodic latency spikes | Checkpoints, autovacuum, background crons | Logs in pgBadger, pg_stat_bgwriter, pg_stat_io |
| Writes slowed after edits | Too many indexes on hot tables | Drop unused ones from pg_stat_user_indexes, use partial |
To avoid falling back into random edits, run through the same seven-step loop every time.
PostgreSQL Query Optimization Checklist
- Find top offenders by
total_exec_timeand abnormalcallsinpg_stat_statements. - Reproduce the query against realistic data volume, not an empty dev database.
- Run
EXPLAIN (ANALYZE, BUFFERS)and read bottom-up; wrap write queries inBEGIN ... ROLLBACK. - Pick the smallest fix: test an index in
hypopg, fix sargability/stats, swapOFFSETfor keyset, or collapse N+1. - Re-run the plan and compare nodes and
Bufferscounts. - Roll out indexes via
CREATE INDEX CONCURRENTLY(outside transactions) and verify the delta inpg_stat_statements. - Add regression guards: SQL query-count tests, session timeouts, and a p95 latency alert.
Following this workflow ensures every database change rests on an actual execution plan and fewer pages read, rather than hoping a new index might help.


