Video in progress
What does the `EXPLAIN` command show, and how is it different from `EXPLAIN ANALYZE`?
EXPLAIN shows the plan the planner chose and its estimated cost without running the query. EXPLAIN ANALYZE actually runs the query and adds the real time of each step and the number of rows returned.
📖 Answer
EXPLAIN ANALYZE
SELECT * FROM orders WHERE user_id = 42;
Index Scan using idx_orders_user_id on orders (cost=0.43..12.50 rows=8 width=64)
(actual time=0.031..0.045 rows=6 loops=1)
Index Cond: (user_id = 42)
Planning Time: 0.120 ms
Execution Time: 0.070 ms
What to look at:
- the node type:
Seq Scan,Index Scan,Hash Join,Sort... rows=8(estimate) versusactual rows=6(reality). If they differ by hundreds of times, the statistics are stale: runANALYZE orders.actual timeshows which node took the most time.
Be careful: EXPLAIN ANALYZE really executes the query. If you want to check a DELETE or UPDATE, wrap it in a transaction:
BEGIN;
EXPLAIN ANALYZE DELETE FROM sessions WHERE expires_at < now();
ROLLBACK;
EXPLAIN (ANALYZE, BUFFERS) additionally shows how many pages were read from cache and how many from disk, which is very useful when you analyze a slow query.
Sign up to mark studied questions and save your progress.