ANSI SQL / UniversalPerformance & Indexing

How to Use EXPLAIN ANALYZE to Optimize Slow SQL Queries

Inspect the query execution plan, index scans vs sequential table scans, execution time, and buffer cache hits.

Quick SQL Solution
Safe (Read / Non-destructive)ANSI SQL / UniversalAdvanced
EXPLAIN (ANALYZE, BUFFERS, COSTS)
SELECT * FROM orders WHERE user_id = 42 ORDER BY created_at DESC;
When to use this scenario:An API endpoint takes 4 seconds to respond, and you need to determine which table scan or join is causing the database bottleneck.

Step-by-Step Query Breakdown

1Run full execution plan with timing and buffers (PostgreSQL)
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT * FROM orders
WHERE customer_id = 1042 AND status = 'completed'
ORDER BY created_at DESC
LIMIT 20;

ANALYZE actually executes the query and compares estimated row counts against actual execution timing in milliseconds.

2MySQL EXPLAIN ANALYZE (MySQL 8.0+)
EXPLAIN ANALYZE
SELECT * FROM orders
WHERE customer_id = 1042
ORDER BY created_at DESC;

Displays the iterator tree with cost, actual time per row, and loop counts.

Critical SQL Pitfalls & Precautions

  • β€’WARNING: EXPLAIN ANALYZE actually executes the statement! If you run "EXPLAIN ANALYZE DELETE ...", the rows WILL be deleted from your database!
Frequently Asked Questions

Optimize Slow Queries (EXPLAIN ANALYZE) - Frequently Asked Questions

Common questions about transactional safety, indexing, and engine compatibility.

"Seq Scan on table (cost=... rows=1000000)" indicates PostgreSQL is reading every single page on disk because no suitable index was found.