Code Reference

EXPLAIN & ANALYZE

Postgres · Reference cheat sheet

EXPLAIN & ANALYZE

Postgres · Reference cheat sheet


📋 Overview

EXPLAIN shows the planner’s chosen plan; EXPLAIN ANALYZE executes the query and adds actual timings/rows. Essential for diagnosing slow queries and verifying indexes.

🔧 Core concepts

OptionAdds
ANALYZEActual runtime stats
BUFFERSShared/hit/read buffer counts
VERBOSEExtra detail
WALWAL generation (newer versions)
SETTINGSRelevant GUCs
Node tipMeaning
Seq ScanFull table read
Index Scan / OnlyUsing index
Nested Loop / Hash / MergeJoin strategies
rows vs actual rowsEstimator accuracy

💡 Examples

Basic:

EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 42;

With buffers:

EXPLAIN (ANALYZE, BUFFERS)
SELECT o.*
FROM orders o
JOIN users u ON u.id = o.user_id
WHERE u.email = 'ada@example.com';

Compare plans:

SET enable_seqscan = off; -- diagnostic only
EXPLAIN ANALYZE SELECT ...;

⚠️ Pitfalls

  • EXPLAIN ANALYZE runs the query — careful with writes (use a transaction + ROLLBACK when testing DML).
  • Stale statistics → bad plans — ANALYZE the tables.
  • Reading plans takes practice — start with the most expensive node (time).

On this page