What does EXPLAIN ANALYZE show you?
IntermediateConceptPostgreSQL
Answer
Short answer
EXPLAIN shows the plan PostgreSQL intends to use for a query — which indexes, join methods and estimated rows/cost. EXPLAIN ANALYZE actually runs the query and adds real timings and row counts for each step, so you can see where the time really goes.
Example
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;
Seq Scan on orders (cost=0.00..18334.00 rows=50 width=64) (actual time=0.03..92.1 rows=48 loops=1)
Filter: (customer_id = 42)
Rows Removed by Filter: 999952
Execution Time: 92.3 ms
Reading it: a Seq Scan read a million rows to return 48 — an index on customer_id is missing.
After CREATE INDEX ON orders(customer_id);:
Index Scan using orders_customer_id_idx on orders (actual time=0.02..0.11 rows=48 loops=1)
Execution Time: 0.2 ms
What to look for
| Sign | Likely issue |
|---|---|
| Seq Scan on a large table with few rows returned | Missing index |
| Estimated rows ≫ or ≪ actual rows | Stale statistics → ANALYZE |
Sort Method: external merge Disk |
work_mem too small or sort not needed |
| Nested Loop over many rows | Missing index on the join key |
Caution
EXPLAIN ANALYZE really executes the statement — wrap UPDATE/DELETE in BEGIN; ... ROLLBACK;.
What to say in the interview
"EXPLAIN shows the planned execution; ANALYZE runs it and shows actual times and row counts per node. I look for sequential scans on big tables, misestimates that point to stale stats, and sorts spilling to disk — and wrap writes in a rolled-back transaction."
More on PostgreSQL
How do you set up PostgreSQL and log in with psql?BeginnerHow do you create a database, tables, users and query data in PostgreSQL?BeginnerHow do you back up and restore a PostgreSQL database?BeginnerWhat is PostgreSQL and why is it so popular?BeginnerHow is PostgreSQL organised: cluster, database, schema and table?BeginnerHow do you connect to PostgreSQL from the command line?Beginner