4 Hours
9. Deep Optimization: EXPLAIN ANALYZE
Engineering
Reading the Database's Mind
When a query is slow, don't guess — Measure. EXPLAIN tells you what the database plans to do. EXPLAIN ANALYZE actually runs the query and gives you the real timing data. Mastering this tool is the hallmark of a Senior Database Engineer.
Anatomy of a Query Plan
When you run EXPLAIN ANALYZE, Postgres returns a tree of Nodes. You read them from the inside out.
SQL
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM users WHERE email = 'p@v.com';
Key Metrics to Watch:
- Seq Scan: The database read every row. This is usually where you add an index.
- Index Scan: The database used an index to find specific rows. (Good).
- Bitmap Heap Scan: A middle-ground where Postgres uses an index to find locations, then pulls data in
batches. - Cost: An arbitrary unit showing the
effortrequired. Lower is better. - Actual Time: The real execution time in milliseconds.
The Role of Buffers
By adding the BUFFERS flag, you can see if data was found in RAM (Hit) or if Postgres had to go to the slow disk (Read). High-performance systems aim for 100% Cache Hits.
Real World Strategy: If you see many
Reads in your explain plan, it means your shared_buffers might be too small, or your query is reading too much unnecessary data from the disk.Knowledge Check
Ready to test your understanding of 9. Deep Optimization: EXPLAIN ANALYZE?