BBackend CourseLeroy Labs
0/0
Search the course

Reading query plans with EXPLAIN ANALYZE & Postgres performance tuning

How the planner works, scan and join types, reading EXPLAIN (ANALYZE, BUFFERS), statistics and ANALYZE, pg_stat_statements, VACUUM and bloat, and a tuning checklist.

● advanced

Reading a plan

EXPLAIN (ANALYZE, BUFFERS)
SELECT b.* FROM bookings b
WHERE b.room_id = '9a..' AND b.academic_year = '2026/2027' AND b.status = 'APPROVED';
Index Scan using idx_bookings_room_period_status on bookings b
    (cost=0.42..8.45 rows=3 width=212) (actual time=0.031..0.036 rows=2 loops=1)
  Index Cond: ((room_id = '9a..') AND (academic_year = '2026/2027') AND (status = 'APPROVED'))
  Buffers: shared hit=4
Planning Time: 0.120 ms
Execution Time: 0.061 ms

How to read it:

  • Read the plan from the innermost node outward.
  • cost is the planner’s estimate in arbitrary units. actual time is real milliseconds per loop.
  • rows estimate vs actual. A large mismatch means bad statistics, and a bad plan follows.
  • Buffers: shared hit pages came from cache; read pages came from disk.
  • loops: multiply the time by loops for nested nodes.

Scan types

Node Meaning
Seq Scan Reads the whole table. Fine for small tables or when returning most rows
Index Scan Walks the index, then fetches rows
Index Only Scan Answers from the index alone (covering index + visibility map); fastest
Bitmap Index/Heap Scan Combines index results, then reads pages in order; good for medium selectivity

Join types

Join Good when
Nested Loop Small outer side + indexed inner side
Hash Join Large unsorted inputs, equality joins
Merge Join Both inputs sorted on the join key

Toolbox

-- top queries by total time (enable the extension first)
SELECT query, calls, total_exec_time, mean_exec_time, rows
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 20;

-- unused indexes
SELECT relname, indexrelname, idx_scan FROM pg_stat_user_indexes WHERE idx_scan = 0;

-- table bloat / dead tuples
SELECT relname, n_dead_tup, last_autovacuum FROM pg_stat_user_tables ORDER BY n_dead_tup DESC;

ANALYZE bookings;         -- refresh planner statistics

MVCC housekeeping

Updates and deletes leave dead tuples behind. Autovacuum reclaims them and updates statistics. A long-running transaction (an idle-in-transaction connection, or a stuck report) prevents cleanup, which leads to bloat and slower queries. Monitor idle in transaction connections and set idle_in_transaction_session_timeout.

Tuning checklist

  1. Find the slow queries with pg_stat_statements, or slow-query logging (log_min_duration_statement = 500ms).
  2. Run EXPLAIN (ANALYZE, BUFFERS) and look for Seq Scans on big tables and bad row estimates.
  3. Add the right index (composite order, partial, covering), or rewrite the query (EXISTS instead of IN, avoid functions on indexed columns, keyset pagination).
  4. Check for N+1 patterns in the ORM (Module 3).
  5. Tune memory: shared_buffers (~25% of RAM), work_mem (per sort or hash, so be careful), effective_cache_size.
  6. Set statement_timeout for the app user, so one runaway query can’t take down the DB.

Check yourself

1. Estimated rows=10, actual rows=500000. What does it suggest?
2. Fastest scan when all needed columns are in the index?
3. What blocks VACUUM from cleaning dead tuples?