How do you use EXPLAIN ANALYZE effectively in PostgreSQL?
Answer
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) is the most comprehensive query analysis tool. Key elements to examine: (1) Node types: Seq Scan (full table — bad for large tables), Index Scan, Index Only Scan (best — no heap access), Bitmap Heap Scan, Hash Join, Merge Join, Nested Loop. (2) Rows estimate vs actual: large discrepancies indicate stale statistics (rows=1 estimate vs actual rows=50000 → run ANALYZE). (3) Cost: cost=startup..total in planner units. (4) Buffers: Buffers: shared hit=X read=Y — high read means cache miss. (5) Loops: actual time is per-loop; multiply by loops for total. (6) Filter: rows removed by filter — indicates a non-indexed filter condition. Use explain.depesz.com or explain.dalibo.com to visualize plans. Always run EXPLAIN ANALYZE on production data, not empty test databases.
Previous
What is pg_cron and how do you schedule jobs in PostgreSQL?
Next
What is the difference between LATERAL joins and correlated subqueries?
More PostgreSQL Questions
View all →- Advanced What is the query planner in PostgreSQL and how does it work?
- Advanced What causes poor query plans and how do you fix them?
- Advanced What is logical replication in PostgreSQL?
- Advanced How do you implement row-level security (RLS) in PostgreSQL?
- Advanced What is table bloat in PostgreSQL and how do you fix it?