Ankit KanojiyaAdvanced

Evergreen guide by Ankit Kanojiya · Advanced · Databases

Query Optimization and Performance Tuning

A workflow for diagnosing slow queries with EXPLAIN, fixing common bottlenecks, and tuning for sustained performance.

Query tuning is a loop: measure, find the bottleneck, change one thing, measure again. Guessing wastes effort, because the slow part is often not where intuition points. The tools below make the real cost visible.

Read the plan first

Every tuning session starts with the execution plan. EXPLAIN shows the planner's chosen strategy and estimated costs; EXPLAIN ANALYZE actually runs the query and reports real timings and row counts.

explain analyze
select c.name, sum(o.total)
from customers c
join orders o on o.customer_id = c.id
where o.created_at >= now() - interval '7 days'
group by c.name;

Read it from the innermost node outward. The two numbers that matter most are the time spent in each node and the gap between estimated and actual rows. A large gap means the planner is working from bad statistics and is likely choosing a poor plan.

Recognize the expensive operators

A handful of plan nodes explain most slow queries:

  • Sequential Scan on a large table where a filter should have used an index.
  • Nested Loop joining many rows, where a hash or merge join would be cheaper.
  • Sort or Hash spilling to disk because work memory is too small.
  • Rows Removed by Filter showing the engine read far more rows than it returned.

Each points to a different fix: a missing index, stale statistics, a memory setting, or a query that fetches too much.

Common fixes

Most wins come from a short list of changes:

  1. Add or adjust an index so the hot filter and join columns are covered.
  2. Select only the columns needed. select * blocks index-only scans and moves extra data.
  3. Filter as early as possible so later operators handle fewer rows.
  4. Replace a correlated subquery that runs per row with a join or a single aggregate.
  5. Refresh statistics with ANALYZE after large data changes.

A correlated subquery is a frequent culprit:

-- Slow: runs the subquery once per customer row.
select c.name,
       (select count(*) from orders o where o.customer_id = c.id)
from customers c;

-- Faster: one grouped pass.
select c.name, count(o.id)
from customers c
left join orders o on o.customer_id = c.id
group by c.name;

Pagination and large result sets

Offset-based pagination grows slower as the offset increases, because the engine still reads and discards every skipped row. Keyset pagination scales far better by seeking from the last seen key.

-- Keyset pagination: stays fast at any depth.
select * from orders
where created_at < '2026-11-01 00:00:00'
order by created_at desc
limit 20;

Server-level tuning

Beyond individual queries, a few settings shape overall behavior:

  • Work memory controls how much a sort or hash can use before spilling to disk.
  • Shared buffers set how much data the engine caches in memory.
  • Autovacuum keeps statistics fresh and reclaims dead rows left by updates and deletes.

Neglecting autovacuum is a classic cause of gradual slowdown: dead tuples accumulate, tables bloat, and plans degrade as statistics age.

Find the worst offenders

Tune where it counts. Extensions and views that track statement statistics reveal which queries consume the most total time, which is usually a frequent medium-cost query rather than one dramatic slow one.

select query, calls, mean_exec_time, total_exec_time
from pg_stat_statements
order by total_exec_time desc
limit 10;

Optimizing the top entries by total time gives the largest system-wide gain.

A repeatable workflow

Put it together into a loop:

  1. Identify the costliest statements from collected statistics.
  2. Capture a plan with EXPLAIN ANALYZE on realistic data volumes.
  3. Form one hypothesis about the bottleneck.
  4. Apply a single change: an index, a rewrite, or a setting.
  5. Re-measure and keep the change only if it genuinely helped.

Summary

Performance tuning rewards discipline over cleverness. Let the execution plan point to the real bottleneck, change one variable at a time, and always validate against production-like data. Small, measured adjustments compound into a system that stays fast as it grows.