AI Hints
Home›PostgreSQL Tutorial›EXPLAIN ANALYZE and Smarter Indexes
PostgreSQL · Lesson 52 of 120

EXPLAIN ANALYZE

What really happened.

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

Explain shows guesses. Explain analyze actually runs the query, and shows the real rows and the real time. Comparing guesses with reality finds most problems.

  • Guesses
  • Real numbers
  • Compare

Estimates vs reality

Explain analyze shows the estimated rows next to the actual rows, and the total time. Run it. The estimate and the actual row counts are close, so the planner has good statistics.

query.sqlsql
EXPLAIN (ANALYZE, BUFFERS OFF, TIMING OFF)
SELECT device, count(*)
FROM page_views
WHERE book_id = 7
GROUP BY device;
Output
                                              QUERY PLAN
----------------------------------------------------------------------------------------
--------------
 HashAggregate  (cost=6301.45..6301.47 rows=2 width=12) (actual rows=2.00 loops=1)
   Group Key: device
   Batches: 1  Memory Usage: 32kB
   ->  Seq Scan on page_views  (cost=0.00..6250.00 rows=10290 width=4) (actual
   rows=10319.00 loops=1)
         Filter: (book_id = 7)
         Rows Removed by Filter: 289681
 Planning Time: 0.174 ms
 Execution Time: 10.884 ms
(8 rows)
Also uses _setup.sql
SELECT setseed(0.42);
CREATE TABLE page_views (
  view_id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id integer NOT NULL,
  book_id     integer NOT NULL,
  device      text NOT NULL,
  viewed_at   timestamptz NOT NULL,
  ms          integer NOT NULL);
INSERT INTO page_views (customer_id, book_id, device, viewed_at, ms)
SELECT 1 + (random() * 499)::int, 1 + (random() * 29)::int,
       (ARRAY['web','web','web','app','app'])[1 + (random() * 4)::int],
       timestamptz '2025-01-01' + (g * interval '100 seconds'),
       50 + (random() * 900)::int
FROM generate_series(1, 300000) g;
VACUUM ANALYZE page_views;
ALTER DATABASE riverside SET max_parallel_workers_per_gather = 0;

What to look for

Look for the slowest step, by actual time. Look for big gaps between estimated and actual rows. Look for sequential scans on large tables, with filters that remove most rows. And remember, analyze really runs the query, even updates.

keyvalue
Slowest nodeactual time
Bad estimatesrows vs actual
Seq Scan + Filtermissing index?
Carefulit really runs

Summary

Explain analyze runs the query and shows real rows and times, so you can find the slow part. Next, indexes on several columns.

Key takeaways
  • ANALYZE
  • Estimated vs actual
  • Real time
Next up: Multicolumn Indexes — order matters