AI Hints
Home›PostgreSQL Tutorial›Indexes and EXPLAIN
PostgreSQL · Lesson 51 of 120

EXPLAIN

Read the plan.

⏱ 2 min read▶ Video at 44:41🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Before running a query, Postgres makes a plan. Explain shows that plan, without running anything. It's the first tool you reach for when a query is slow.

  • Make a plan
  • EXPLAIN shows it
  • Find slow parts

A join plan

Explain shows a tree of steps. The innermost lines run first. Each line has an estimated cost and number of rows. Run it. A hash join, built from two scans, then a sort.

query.sqlsql
EXPLAIN
SELECT c.country, count(*)
FROM orders o JOIN customers c USING (customer_id)
GROUP BY c.country
ORDER BY count(*) DESC;
Output
                                      QUERY PLAN
---------------------------------------------------------------------------------------
 Sort  (cost=60.59..60.60 rows=6 width=14)
   Sort Key: (count(*)) DESC
   ->  HashAggregate  (cost=60.45..60.51 rows=6 width=14)
         Group Key: c.country
         ->  Hash Join  (cost=21.25..52.46 rows=1598 width=6)
               Hash Cond: (o.customer_id = c.customer_id)
               ->  Seq Scan on orders o  (cost=0.00..26.98 rows=1598 width=4)
               ->  Hash  (cost=15.00..15.00 rows=500 width=10)
                     ->  Seq Scan on customers c  (cost=0.00..15.00 rows=500 width=10)
(9 rows)

Reading a plan

Seq scan reads a whole table. Index scan uses an index. Hash join and nested loop combine tables. Cost is in made up units, first to start, then total. And rows is Postgres's guess.

TermMeans
Seq Scanwhole table
Index Scanvia an index
Hash Join / Nested Loopjoin methods
cost=a..bstart..total
rows=nestimated rows

Summary

Explain shows the plan as a tree of steps, with estimated costs and rows. Next, explain analyze, which shows what really happened.

Key takeaways
  • EXPLAIN
  • Plan tree
  • Estimates
Next up: EXPLAIN ANALYZE — what really happened