Hamza Janzaib avatar
AboutResumeProjectsWorkBlogContact
Home/Blog/Databases, Prisma & Redis/Solving PostgreSQL Query Performance Problems

Solving PostgreSQL Query Performance Problems

Read the plan, not the guesses: a workflow for diagnosing and fixing slow PostgreSQL queries.

By Hamza JanzaibNovember 28, 202614 min readAdvanced
Paste it into ChatGPT, Claude or any AI assistant.
  • postgresql
  • performance
  • indexes
  • sql
On this page ยท 14 sections
  • Step 1: Find the queries that matter
  • Step 2: Read the plan
  • Common plan nodes
  • Step 3: Fix with the right index
  • Partial indexes
  • Covering indexes
  • Why the planner ignores your index
  • Step 4: Fix query shape, not just indexes
  • Step 5: Keep the database healthy
  • Common mistakes
  • Testing and validation
  • Production considerations
  • Best practices
  • Conclusion

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:

sql
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:

sql
-- postgresql.conf (or ALTER SYSTEM)log_min_duration_statement = 500   -- log anything slower than 500 ms

On 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:

sql
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:

text
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 ms

How to read it:

  • Plans are trees. Read from the innermost, most indented node outward.
  • cost is the planner's estimate in arbitrary units; actual time is real milliseconds (first row..last row).
  • rows estimated 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: 1998957 is the red flag here: the database read two million rows to keep about a thousand.
  • loops multiplies per-loop time. A node with loops=5000 and actual time=0.1 still costs about 500 ms.
  • BUFFERS shows how much data came from cache (shared hit) vs disk (read).

EXPLAIN ANALYZE executes the statement. For UPDATE or DELETE, run it inside BEGIN; ... ROLLBACK;.

Common plan nodes

NodeMeaningWatch for
Seq ScanReads the whole tableFine for small tables; bad when it discards most rows
Index ScanWalks an index, fetches rowsGood for selective filters
Index Only ScanAnswers from the index aloneBest case; needs a visibility map kept fresh by VACUUM
Bitmap Heap ScanCollects matches, then reads pages in orderCommon middle ground for moderately selective filters
Nested LoopFor each outer row, probe the inner sideGreat with an index on the inner side; terrible without
Hash JoinBuilds a hash table of one sideGood for large joins; watch memory (work_mem)
SortSorts rowsSort 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:

sql
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) helps WHERE a = ? but generally not WHERE 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:

sql
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:

sql
CREATE INDEX CONCURRENTLY idx_orders_cover  ON orders (customer_id, created_at DESC) INCLUDE (total_cents, status);

Why the planner ignores your index

CauseExampleFix
Function on the columnWHERE lower(email) = 'a@x.com'Expression index: CREATE INDEX ON users (lower(email))
Type mismatchComparing a text column to a numberMatch types explicitly
Leading wildcardLIKE '%term%'pg_trgm + GIN index
Stale statisticsAfter a big data loadANALYZE table_name;
Low selectivityFilter matches 40% of rowsA sequential scan really is cheaper; consider a different design
Wrong column orderIndex (b, a) for WHERE a = ?Reorder or add an index

For text search with wildcards:

sql
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:

sql
-- 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.
  • ANALYZE after bulk loads so the planner has accurate statistics.
  • Bloat (tables and indexes with lots of dead space) slows scans. Monitor it, and use REINDEX CONCURRENTLY when 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_mem affects 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 EXPLAIN without ANALYZE and trusting estimates.
  • Forgetting CONCURRENTLY and 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:

  1. The EXPLAIN (ANALYZE, BUFFERS) output on production-like data.
  2. The query's mean_exec_time in pg_stat_statements after the change (reset stats with pg_stat_statements_reset() when comparing).
  3. 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.

Further reading

  • www.postgresql.org/docs/current/using-explain.html

Hamza Janzaib

Full-Stack Developer based in Karachi, Pakistan. Building web apps, APIs and cloud infrastructure. About me


Related articles

Databases, Prisma & RedisNovember 28, 202612 min readIntermediate

Solving Prisma ORM Performance and Query Problems

Query logging, select over include and connection pooling: the usual suspects behind slow Prisma code.

Databases, Prisma & RedisNovember 28, 202613 min readIntermediate

Implementing Redis Caching to Reduce API Response Times

Cache-aside with Redis, done carefully: keys, TTLs, invalidation and protection against stampedes.

Next.js, React & TypeScriptNovember 28, 202613 min readIntermediate

Managing API Caching and Data Fetching in Next.js

A mental model for Next.js caching layers and a repeatable pattern for fetching, caching and revalidating API data.

Built by Hamza Janzaib

PrivacyTerms