Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Postgres: Reading EXPLAIN in Depth

Tested 2026-11-25 on Debian GNU/Linux 13 (trixie), Raspberry Pi 4 Model B (4 GB, 4 cores, aarch64); Docker Engine 29.4.0, no VM: containers share the 4 CPUs and 4 GB · with PostgreSQL 19.0 (Docker image postgres:19.0), Docker 29.4.0 · by Vivek Sahu (@viv1) · CC BY 4.0

Your shop’s My orders page asks Postgres for one customer’s orders: 7 rows out of 2,000,000.

It takes 148 ms on a Raspberry Pi 4, because Postgres goes through all 16,667 pages of the table to find them.

The SQL looks fine. The reason is in the plan, and EXPLAIN shows it to you.

One index later, the same query touches 13 pages and takes 0.414 ms.

Reading the plan is how you find out why a query is slow. This course teaches you to read one, on a database you set up and break yourself, with every plan and number in it taken from real runs.

You should know how to write a SELECT with WHERE, JOIN, GROUP BY and ORDER BY, and how to run a command in a terminal. You don’t need to know Postgres: lesson 1 explains the few pieces reading a plan depends on (pages, indexes, the planner).

By the end you’ll be able to:

  • take a slow query from your app’s logs, run EXPLAIN ANALYZE on it, and say which step costs the time and why;
  • tell whether an index would help, which one, and prove it with before/after numbers;
  • recognise when the planner guessed the row count wrong, and fix it;
  • find the slowest queries of a running database before anyone reports them.

How it works

Each lesson starts from an animated, step-by-step picture (press Play, or step with the arrow keys), then explains in plain words, with optional Go deeper sections for the internals. Each practical has you do it yourself on your own Postgres: requirements, a hint, a hidden solution, a “predict first” question and a part where you break it on purpose. One script, ./lab, does the rest:

  • ./lab setup pN gets what a practical needs that isn’t its topic: the Postgres container, the data, the files it hands out. It says one line per step (every command and its output go to lab.log), and keeps what you already have.
  • ./lab check pN tells you whether your work is right. It only reads.
  • ./lab reset pN starts you at a practical with the earlier ones’ solutions in place, after a Break it gone too far or a month away. It asks first, removes only the container and volume that ./lab setup made (it labels them), and never touches your files.

All you need is Docker on macOS or Linux. Postgres 19 runs in a container that ./lab setup p0 starts.

Path

LessonPracticalYou’ll be able to
1 · Why a query is slow0 · Your Postgressee a plan, and why the same query takes 148 ms or 0.414 ms
2 · Reading a plan1 · Where the time goesfind the node that costs the time; fix it with an index
3 · How rows are foundtell when an index is used, and when it rightly isn’t
4 · Estimates and joins2 · When the planner guesses wrongspot a bad row estimate and the plan it causes; fix statistics and memory
5 · In production3 · Capstone: slow-query huntfind and fix the slowest queries of a running app
What your folder will look like
 ~/pg-explain/
 ├── lab              the lab script: setup, check, reset (from Practical 0)
 ├── report.md        your capstone report (Practical 3)
 └── sql/             mounted in the container at /sql
     ├── shop.sql     creates and fills customers and orders
     ├── cities.sql   adds a city to every customer (Practical 2)
     └── app/         the app's three queries (Practical 3)

1 · Why a query is slow

In one sentence: Postgres decides how to run your query before it runs it (that decision is the plan), and a slow query is often one whose plan reads far more data than the answer needs; EXPLAIN shows you the plan.

The problem

Your shop has a My orders page. It runs one query:

SELECT * FROM orders WHERE customer_id = 4242;

It returns 7 rows. With 2,000,000 orders in the table, on the machine this course was written on, it takes 148 ms. Nothing in the SQL tells you why: the query is short and correct. The answer is in what Postgres did to answer it.

The idea: a query has a plan

SQL says what you want (“the orders of customer 4242”), not how to find them. Before running a query, a part of Postgres called the planner considers the ways it could get the answer, estimates the cost of each, and picks the cheapest. The chosen way is the plan.

EXPLAIN in front of a query prints that plan without running it:

EXPLAIN SELECT * FROM orders WHERE customer_id = 4242;
                                QUERY PLAN                                
--------------------------------------------------------------------------
 Gather  (cost=1000.00..28084.77 rows=11 width=37)
   Workers Planned: 2
   ->  Parallel Seq Scan on orders  (cost=0.00..27083.67 rows=5 width=37)
         Filter: (customer_id = 4242)

Read it from the most indented line outwards. Seq Scan on orders means “read the whole orders table, row by row”. Filter is the test each row must pass. rows=11 is the planner’s estimate of how many rows come out: it hasn’t run anything yet. (Parallel and Gather: the reading is split between several processes, see Go deeper.)

What Postgres is reading: pages

To see why a Seq Scan is slow, you need one fact about storage. A table is kept on disk as pages of 8 kB. orders is 16,667 pages, 130 MB, about 120 rows per page. Postgres works on whole pages, never single rows, and keeps recently used ones in its own cache.

 orders: 16,667 pages
 ┌──────┬──────┬──────┬─────┬──────┬─────┬──────┐
 │ p 0  │ p 1  │ p 2  │ ... │ 5439 │ ... │16666 │   each page: about 120 rows
 └──────┴──────┴──────┴─────┴──────┴─────┴──────┘
                                ▲ one of customer 4242's rows

Rows are stored roughly in the order they were inserted. Customer 4242 placed 7 orders at different times, so those 7 rows sit on 7 different pages, from page 5,439 to page 15,771. Nothing in the table says where they are.

What actually happened: EXPLAIN ANALYZE

EXPLAIN ANALYZE runs the query and adds what really happened next to each estimate:

EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 4242;
 Gather  (cost=1000.00..28084.77 rows=11 width=37) (actual time=69.078..148.036 rows=7.00 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   Buffers: shared hit=14250 read=2417
   ->  Parallel Seq Scan on orders  (cost=0.00..27083.67 rows=5 width=37) (actual time=78.566..127.270 rows=2.33 loops=3)
         Filter: (customer_id = 4242)
         Rows Removed by Filter: 666664
...
 Execution Time: 148.256 ms

Three lines tell the story:

LineSays
rows=7.00 on the top line7 rows came out (the estimate was 11)
Rows Removed by Filter: 666664on average 666,664 rows per process (loops=3) were checked and thrown away: 1,999,993 in all
Buffers: shared hit=14250 read=2417pages touched: hit were already in Postgres’s cache, read were not. 14,250 + 2,417 = 16,667: the whole table

So the 148 ms is spent going through every page and checking every row, to keep 7.

A different plan: with an index

An index is a separate structure, sorted by a column, where each entry points to the page holding its row. Like the index at the back of a book: look up “4242”, get the page numbers. Building one on customer_id took 2.5 seconds and 18 MB:

CREATE INDEX orders_customer_id_idx ON orders (customer_id);
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 4242;
 Bitmap Heap Scan on orders  (cost=4.51..47.80 rows=11 width=37) (actual time=0.118..0.231 rows=7.00 loops=1)
   Recheck Cond: (customer_id = 4242)
   Heap Blocks: exact=7
   Buffers: shared hit=13
   ->  Bitmap Index Scan on orders_customer_id_idx  (cost=0.00..4.51 rows=11 width=0) (actual time=0.060..0.060 rows=7.00 loops=1)
         Index Cond: (customer_id = 4242)
         Index Searches: 1
         Buffers: shared hit=6
...
 Execution Time: 0.414 ms

Same query, same 7 rows: 0.414 ms, about 360 times faster. The plan changed: the inner node looks 4242 up in the index, the outer one reads only the pages it was pointed to (Heap Blocks: exact=7, “heap” being Postgres’s word for the table itself). 13 pages touched instead of 16,667. Lesson 3 explains why this is a two-step Bitmap scan.

This is the whole course in miniature: a query is slow because of its plan, and EXPLAIN ANALYZE shows which node did the work, how many rows it threw away, and how many pages it touched.

Try it on your computer

Practical 0 · Your Postgres: get Postgres 19 running in Docker with this shop, see these plans yourself, and find out the hard way that EXPLAIN ANALYZE really runs what you give it.

Go deeper: Gather, workers, and per-loop averages

Workers Launched: 2 means Postgres started 2 helper processes. With the main process (the leader), 3 processes each scanned part of the table: that’s loops=3 on the Parallel Seq Scan. Gather collects their rows.

For a node that ran several times, rows, Rows Removed by Filter and the times are averages per loop, not totals (Using EXPLAIN, “EXPLAIN ANALYZE”). That’s how rows=2.33 can appear: 7 rows over 3 loops. Multiply by loops to get totals: 666,664 × 3 = 1,999,992, the 1,999,993 thrown-away rows give or take rounding. Lesson 2 reads loops in joins, where it matters more.

Pages counted as read came from the operating system, which may itself have had them cached, so read doesn’t mean a disk read. Postgres 19 prints the Buffers line with EXPLAIN ANALYZE without being asked.

Go deeper: where a row lives

Every row has a hidden address, ctid: (page, position in the page). Ask for it:

SELECT ctid, id, created_at FROM orders WHERE customer_id = 4242 ORDER BY id;
    ctid     |   id    |       created_at       
-------------+---------+------------------------
 (5439,109)  |  652789 | 2024-12-21 02:31:23+00
 (6542,120)  |  785160 | 2025-03-03 02:42:00+00
...
 (15771,47)  | 1892567 | 2026-10-26 12:30:49+00

The page number grows with the order’s id and date: the rows went in in that order. An index entry stores exactly this address, which is how a lookup jumps straight to page 5,439. The page format is in Database Page Layout.

Common misunderstandings

  • “EXPLAIN shows how long the query takes.” Plain EXPLAIN only shows the plan and estimates. Times, real row counts and pages come from EXPLAIN ANALYZE, which runs the query.
  • “An index makes every query faster.” It helps queries that need a small part of the table. Lesson 3 shows the planner ignoring an index, rightly.

Check yourself

1. A scan node shows rows=20, Rows Removed by Filter: 50, loops=1 and Buffers: shared hit=4. Is this node why your query is slow? Almost certainly not. It checked 70 rows and touched 4 pages: very little work. A node worth fixing does a lot of work for its answer: the Seq Scan in this lesson threw away 1,999,993 rows and touched 16,667 pages to keep 7. Look elsewhere in the plan.
2. A query takes 400 ms. After you add an index, EXPLAIN ANALYZE shows the same plan as before and 12 ms. What happened? The index changed nothing: the plan is the same. The difference is most likely the cache: the first run read pages from disk, the second found them in memory (compare read= and hit= in Buffers). Always run twice and compare like with like; lesson 5 comes back to this.
3. Suppose one customer had 40,000 orders, placed over two years. Would the index save as much work for them as for customer 4242? No. The index still finds the rows directly, but those rows sit on thousands of different pages, and each of those pages still has to be read. The saving shrinks as the share of the table you need grows; the planner weighs exactly this when it chooses between the index and a Seq Scan, which lesson 3 measures.

Next: Practical 0 · Your Postgres, then lesson 2 · Reading a plan.

2 · Reading a plan

In one sentence: a plan is a tree of nodes that pass rows upwards; read it from the leaves up, subtract each node’s children from its time, and the node with the most time of its own is where your query is slow.

The problem

The shop’s finance page asks for October’s revenue per country:

SELECT c.country, count(*) AS orders, sum(o.total_cents) AS revenue_cents
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= '2026-10-01' AND o.created_at < '2026-11-01'
GROUP BY c.country
ORDER BY revenue_cents DESC;

It returns 8 rows in 584 to 683 ms (five runs; below, the 683 ms one). Which node is slow?

This lesson switches parallel workers off for the session (SET max_parallel_workers_per_gather = 0;) so each node runs once. With them on, the query took 283 ms, with extra Gather and Partial nodes to read.

The tree

 Sort  (cost=55534.99..55535.01 rows=8 width=19) (actual time=682.952..682.959 rows=8.00 loops=1)
   Sort Key: (sum(o.total_cents)) DESC
   ->  HashAggregate  (cost=55534.79..55534.87 rows=8 width=19) (actual time=682.881..682.891 rows=8.00 loops=1)
         Group Key: c.country
         ->  Hash Join  (cost=47399.41..55095.34 rows=58593 width=7) (actual time=501.354..650.863 rows=56987.00 loops=1)
               Hash Cond: (c.id = o.customer_id)
               ->  Seq Scan on customers c  (cost=0.00..3860.00 rows=200000 width=11) (actual time=0.055..38.196 rows=200000.00 loops=1)
               ->  Hash  (cost=46667.00..46667.00 rows=58593 width=12) (actual time=500.686..500.688 rows=56987.00 loops=1)
                     ->  Seq Scan on orders o  (cost=0.00..46667.00 rows=58593 width=12) (actual time=427.528..472.121 rows=56987.00 loops=1)
                           Filter: ((created_at >= '2026-10-01 00:00:00+00'::timestamp with time zone) AND (created_at < '2026-11-01 00:00:00+00'::timestamp with time zone))
                           Rows Removed by Filter: 1943013
...
 Execution Time: 683.404 ms

The first line and each line starting with -> is a node; the lines under a node without an arrow are its details. Indentation is the tree: a node’s children are the nodes indented one level deeper under it, and rows flow up from them.

 Sort                     8 rows
 └── HashAggregate        8 rows: one per country
     └── Hash Join        56,987 rows: orders with their customer's country
         ├── Seq Scan on customers   200,000 rows
         └── Hash                    56,987 rows, in a lookup table
             └── Seq Scan on orders  56,987 kept, 1,943,013 removed

The numbers on each node line

PartEstimate or realMeans
cost=47399.41..55095.34estimatethe planner’s price: before the first row ..to the last, in arbitrary units (Go deeper)
rows=58593estimatehow many rows the planner expects the node to return
actual time=501.354..650.863realms until the first row ..until the last
rows=56987.00realrows the node returned
width=7estimateaverage size of a row, in bytes
loops=1realhow many times the node ran

Compare estimate with real first. Here the planner expected 58,593 October orders and got 56,987: close. Lesson 4 is about when they’re far apart.

Finding the slow node: subtract the children

A node’s actual time includes its children. Sort says 683 ms because everything below it ran before Sort could finish. To find what a node cost on its own, take its last-row time and subtract its children’s:

NodeLast row atMinus childrenOwn time
Seq Scan on orders472.1nothing472 ms
Hash500.7472.129 ms
Seq Scan on customers38.2nothing38 ms
Hash Join650.9500.7 + 38.2112 ms
HashAggregate682.9650.932 ms
Sort683.0682.90.1 ms

The Seq Scan on orders is 69% of the query. Its own lines say why: it threw away 1,943,013 rows to keep 56,987. Its first row came out only after 427 ms: October’s orders start on page 15,380 of 16,667.

loops: when a node runs many times

A Nested Loop join runs its inner side once per outer row. Customers 4240 to 4249 with their orders:

SELECT c.email, o.id, o.total_cents FROM customers c JOIN orders o ON o.customer_id = c.id
WHERE c.id BETWEEN 4240 AND 4249;
 Nested Loop  (cost=4.93..487.74 rows=100 width=34) (actual time=0.156..1.499 rows=88.00 loops=1)
   ->  Index Scan using customers_pkey on customers c  (cost=0.42..8.62 rows=10 width=30) (actual time=0.088..0.100 rows=10.00 loops=1)
   ->  Bitmap Heap Scan on orders o  (cost=4.51..47.80 rows=11 width=20) (actual time=0.029..0.130 rows=8.80 loops=10)

It ran the Bitmap Heap Scan 10 times. With loops above 1, actual time and rows are averages per run (Using EXPLAIN): multiply them by loops. 0.130 ms × 10 = 1.3 ms of the Nested Loop’s 1.5 ms, and 8.80 × 10 = 88 rows.

Parallel loops run at the same time: under a Gather, multiply rows but not time (in Practical 1, 170 ms × 3 would exceed the whole 204 ms query).

Buffers: pages, per node

Each node’s Buffers line (cut above) includes its children. The Hash Join’s shared hit=15402 read=3125 is the customers scan’s 1,860 hits plus the Hash’s 13,542 hits and 3,125 reads.

CountMeans
hitpages found in Postgres’s own cache
readpages not in its cache, fetched from the operating system
dirtiedpages this query changed that had no unsaved changes before
writtenchanged pages this query had to save to disk to make room in the cache

written= is about what ran before, not about your query. Postgres’s cache (shared_buffers, 128 MB here) holds pages other statements changed and nobody has saved yet. To make room for its own pages, your query may have to save some first (EXPLAIN, BUFFERS). After a 2,000,000-row UPDATE of another table, a plain count of orders showed:

   Buffers: shared read=16667 written=14

The same count straight after showed no written= at all. In Practical 0, written=147 appeared right after loading the data: a note about the server’s state at that moment, not about the query.

Try it on your computer

Practical 1 · Where the time goes: find the slow node in “the 20 newest pending orders”, try two indexes, measure each, and break it with one function call.

Go deeper: how the planner priced the Seq Scan on orders

cost is in made-up units where reading one page in order costs 1 (seq_page_cost). The settings, from pg_settings: seq_page_cost 1, cpu_tuple_cost 0.01 per row, cpu_operator_cost 0.0025 per comparison. The Seq Scan on orders reads 16,667 pages, looks at 2,000,000 rows, and makes two comparisons per row (created_at >= and <):

 16,667 × 1  +  2,000,000 × 0.01  +  2,000,000 × 2 × 0.0025
 = 16,667    +  20,000            +  10,000                   = 46,667

That’s the cost=0.00..46667.00 on the node. customers: 1,860 pages + 200,000 × 0.01 = 3,860. The formula is in Using EXPLAIN. Every other node adds its own estimate on top of its children’s, which is why costs, like times, grow towards the top.

Common misunderstandings

  • “The top node is the slowest.” Its time includes everything below it. Subtract the children first.
  • “cost is in milliseconds.” It’s in planner units: never compare it with actual time.

Check yourself

1. A Nested Loop's inner Index Scan shows actual time=0.020..0.025 rows=1.00 loops=50000. The query takes 1.4 s. Is the Index Scan a problem? 0.025 ms × 50,000 = 1,250 ms: most of the query. Each lookup is fast, but there are 50,000 of them. The fix is usually not a faster lookup but fewer of them (another join method, or fewer outer rows), which lesson 4 covers.
2. A Hash node shows actual time=900.1..900.1, its only child actual time=0.1..880.0. Which node do you look at? The child: it took 880 ms of its own. The Hash took 900.1 − 880.0 = 20.1 ms.
3. You run EXPLAIN ANALYZE twice. The first run shows written=300, the second none. Is your query writing data? No. It saved pages that earlier statements had changed, to free room in the cache. A read-only query can do that. The second run found no such pages to save.

Next: Practical 1 · Where the time goes, then lesson 3 · How rows are found.

3 · How rows are found

In one sentence: Postgres finds rows by reading the whole table, by jumping through an index, or by a mix of the two, and it picks by estimating how much of the table you need; an index it can’t match to your condition is never used at all.

The problem

After Practical 1, orders has an index on (status, created_at). Yet this query ignores it and reads the whole table:

SELECT * FROM orders WHERE status = 'delivered';
 Seq Scan on orders  (cost=0.00..41667.00 rows=1797533 width=37) (actual time=0.055..606.950 rows=1800352.00 loops=1)
   Filter: (status = 'delivered'::text)
...
 Execution Time: 784.485 ms

Is the planner wrong? And why did lower(status) make the index useless in Practical 1?

Four ways to find rows

NodeWhat it doesYou’ve seen it
Seq Scanreads every page in order, tests every rowlesson 1, before the index
Index Scanwalks the index, jumps to each matching row’s page; rows come out in index orderPractical 1, Index Scan Backward
Bitmap Index Scan + Bitmap Heap Scancollects the pages from the index first, then reads them in page order, each once, testing the condition again (Recheck Cond)lesson 1, after the index
Index Only Scananswers from the index alone, without reading the tablebelow

Only the index scans (Index Scan, Index Only Scan) hand rows over in index order, so they can replace a Sort and, with a LIMIT, stop early: Practical 1’s LIMIT 20 touched 10 pages. A Bitmap scan returns rows in page order, but reads each page once, which pays off when many rows match.

How much of the table you need decides

status has four values, in very different amounts:

statusrowsshare
delivered1,800,35290.0%
shipped120,1276.0%
pending59,6063.0%
cancelled19,9151.0%

For three of them, here is the plan the planner chose, and the same query with that plan forbidden (SET enable_bitmapscan = off; SET enable_indexscan = off; or SET enable_seqscan = off;, test switches only):

WHERE status =Planner choseTimeForced alternativeTime
'cancelled' (1%)Bitmap scan57 msParallel Seq Scan218 ms
'shipped' (6%)Bitmap scan214 msParallel Seq Scan214 ms
'delivered' (90%)Seq Scan784 msBitmap scan1,099 ms

The planner was right each time, or level. For 90% of the table, the forced Bitmap scan read 25,538 pages: all 16,667 of the table plus 8,871 of the index.

The surprising row is the first. 1% of the rows were spread over 70% of the pages:

 Bitmap Heap Scan on orders  (cost=508.58..18182.99 rows=18600 width=37) (actual time=10.966..54.187 rows=19915.00 loops=1)
   Recheck Cond: (status = 'cancelled'::text)
   Heap Blocks: exact=11673

19,915 rows on 11,673 of 16,667 pages: cancelled orders are scattered through the table. Pages are what costs, so the planner estimates both how many rows match (rows=18600) and how many pages they’ll take.

When the index can’t be used at all

An index can only answer conditions on the column as it is stored:

ConditionWhat happensFix
lower(status) = 'pending'Seq Scan, 815 ms (Practical 1)compare the column itself, or index lower(status)
customer_id = 4242.0Seq Scan, 259 msuse the column’s type: customer_id = 4242

The second has no function in it. 4242.0 is a numeric, customer_id a bigint, so Postgres converts the column to compare them:

         Filter: ((customer_id)::numeric = 4242.0)

Look for :: on the column side of a Filter.

Settings that tilt the choice

The planner prices reading a page in order at seq_page_cost = 1 and jumping to a page at random_page_cost = 4 (Planner cost constants). Lowering it makes index scans look cheaper. Five alternating runs of each on the Raspberry Pi 4 (alternating, so the cache differs from the single runs in the table above):

WHERE status = 'shipped'Plan5 runs
default (random_page_cost = 4)Bitmap scan245–283 ms
SET random_page_cost = 1.1Index Scan433–448 ms

A cost setting is a guess about your hardware; change it only when EXPLAIN ANALYZE on your own queries shows the new plans are faster.

Try it on your computer

Try the three status queries on your data, with and without the switches above (RESET ALL; afterwards).

Go deeper: Index Only Scan and the visibility map

Counting the cancelled orders of 2026 needs only status and created_at, both in the index:

SELECT count(*) FROM orders WHERE status = 'cancelled' AND created_at >= '2026-01-01';
   ->  Index Only Scan using orders_status_created_at_idx on orders  (cost=0.43..241.57 rows=6057 width=0) (actual time=0.155..2.272 rows=6526.00 loops=1)
         Heap Fetches: 0
...
 Execution Time: 3.476 ms

3.5 ms, 37 pages. The index doesn’t store whether a row is visible to your transaction. Postgres keeps a visibility map, one bit per table page meaning “every row here is visible to everyone”, and skips the table only for pages with the bit set (Index-Only Scans).

Heap Fetches: 0 means it never had to look. VACUUM, Postgres’s cleanup pass, sets those bits; autovacuum runs it in the background (Routine Vacuuming); on a table with many recent changes, Heap Fetches climbs and the advantage goes.

Go deeper: skip scan, an index used without its first column

Lesson 2’s revenue query filters on created_at alone. Since Practical 1, it uses the (status, created_at) index, whose first column isn’t in the query at all:

                     ->  Bitmap Index Scan on orders_status_created_at_idx  (cost=0.00..1763.04 rows=59688 width=0) (actual time=8.549..8.550 rows=56987.00 loops=1)
                           Index Searches: 9

Index Searches: 9: instead of one search, the index was searched 9 times for the 4 status values, skipping between values and looking up October within them (Multicolumn Indexes). The query went from 584–683 ms to 250 ms, with parallel workers off as in lesson 2. It works because status has only four values; with thousands, an index starting with created_at would be the one to build.

Common misunderstandings

  • “A Seq Scan means a missing index.” For 90% of the table it’s the fastest plan. Check how many rows the scan returns before adding an index.
  • “An index on a column helps any condition on that column.” Only conditions on the column as stored: a function or a type conversion on the column side turns it off.

Check yourself

1. A plan shows Seq Scan on users with Filter: (lower(email) = 'a@b.c') and an index exists on users (email). Why isn't it used, and what are your two options? The index stores email, the condition is on lower(email). Either compare email directly (if emails are stored lowercase), or create an index on lower(email).
2. WHERE status = 'shipped' returns 6% of the rows, and the Bitmap Heap Scan shows Heap Blocks: exact=16657. Why isn't an index much help here? 16,657 is nearly every one of the 16,667 pages. The index finds the rows, but they're on almost every page, so the scan reads nearly the whole table anyway. It measured the same as a parallel Seq Scan (214 ms).
3. Your plan shows Index Only Scan with Heap Fetches: 48000. What does that tell you? For 48,000 rows the visibility map didn't mark the page all-visible, so Postgres read the table after all. The table has had many recent changes not yet vacuumed; the scan is an Index Scan in disguise.

Next: lesson 4 · Estimates and joins.

4 · Estimates and joins

In one sentence: the planner builds every node for the number of rows it expects, an estimate taken from statistics that ANALYZE collects from a sample; when the estimate is far from the real count, the join method and the memory it plans for are made for a different query.

The problem

In Practical 1’s Break it, the lower(status) scan expected rows=4167 per process and returned 19,868.67. With parallel workers off, the same condition (SELECT * FROM orders WHERE lower(status) = 'pending'):

 Seq Scan on orders  (cost=0.00..46667.00 rows=10000 width=37) (actual time=0.996..2079.001 rows=59606.00 loops=1)

10,000 expected, 59,606 found. Where does 10,000 come from? And why care, when the rows returned are right anyway? Every node above the scan is chosen for the rows the planner expects: a join chosen for 10 rows can be wrong for 50,000.

Where estimates come from

ANALYZE reads a random sample of a table, 30,000 rows here (300 × default_statistics_target, which is 100), and stores a summary of each column in pg_stats (Statistics Used by the Planner). Autovacuum reruns it when enough rows change.

SELECT n_distinct, most_common_vals, most_common_freqs FROM pg_stats
WHERE tablename = 'orders' AND attname = 'status';
          4 | {delivered,shipped,pending,cancelled} | {0.9009333,0.0596,0.029833334,0.009633333}

For status = 'pending', the planner multiplies the value’s share by the table’s row count (reltuples in pg_class, 2,000,000): 0.029833334 × 2,000,000 = 59,667, the rows=59667 that EXPLAIN shows. The real count is 59,606.

It’s a sample, so every ANALYZE gives slightly different estimates. The next one on the same data gave 56,933, and yours will differ again.

When there is nothing to look up

The statistics describe status, not lower(status). For = on an expression it has no statistics for, the planner assumes 200 distinct values (DEFAULT_NUM_DISTINCT in selfuncs.h), so 1/200 = 0.5% of the rows: 2,000,000 × 0.005 = 10,000. Practical 1’s rows=4167 is the same guess per process: with two workers, the planner divides by 2.4, because the leader process counts for 0.4 of a worker.

You can give it statistics on the expression:

CREATE STATISTICS orders_lower_status_stats ON (lower(status)) FROM orders;
ANALYZE orders;
 Seq Scan on orders  (cost=0.00..46667.00 rows=56933 width=37)

Right after CREATE STATISTICS it was still 10,000: CREATE STATISTICS declares; ANALYZE collects.

For AND, the planner multiplies the two shares, as if unrelated: wrong when a city tells you the country. Practical 2 measures it.

Three ways to join

JoinHow it worksFast when
Nested Loopfor each row of the outer side, looks up its matches on the inner side, usually through an indexthe outer side has few rows
Hash Joinreads one side into a hash table in memory, then streams the other through itmany rows, in no useful order
Merge Joinreads both sides sorted on the join key and walks them togetherboth come sorted already, from an index

Two of lesson 2’s queries, forced into each method in turn (SET enable_nestloop = off; and so on, parallel workers off, the second and third of three runs; the planner’s own choice in bold):

QueryNested LoopHash JoinMerge Join
10 customers with their orders (88 rows)1.6–1.7 ms750–773 ms107–108 ms
October’s revenue (56,987 orders)690–704 ms252–263 ms327–338 ms

For 10 customers, the Hash Join reads all 2,000,000 orders; the Nested Loop makes 10 index lookups. For October, the Nested Loop looks up a customer 49,564 times; the Hash Join reads the 200,000 customers once.

The planner picks by the estimated rows. Here both were close; when one is far off, it picks the method for the wrong row count. Practical 2 has you find one.

Memory: work_mem

Each Sort and each hash table gets work_mem of memory, 4 MB by default; hash tables get twice that (hash_mem_multiplier = 2) (Resource Consumption). What doesn’t fit goes to temporary files on disk. Sorting this year’s orders by total:

 Sort  (cost=114655.42..116281.60 rows=650472 width=12) (actual time=746.517..956.474 rows=656205.00 loops=1)
   Sort Key: total_cents DESC
   Sort Method: external merge  Disk: 14184kB
   Buffers: shared hit=8664, temp read=1773 written=1782

external merge Disk: 14184kB is a sort that spilled; temp counts its temporary file pages. With SET work_mem = '64MB';: quicksort Memory: 45083kB, 921–929 ms instead of 1,031–1,047 ms. A spill cost little.

The planner knows work_mem too: it prices a hash that won’t fit with its spill to disk, and may then prefer another plan. That choice can cost far more than a spill: Practical 2 has one.

Try it on your computer

Practical 2 · When the planner guesses wrong: a backlog the statistics haven’t seen, two columns that go together, and a report that needs more memory.

Go deeper: Memoize, a Nested Loop that remembers

In the forced Nested Loop for October, a Memoize node sat between the join and its customer lookup:

               ->  Memoize  (cost=0.43..0.61 rows=1 width=11) (actual time=0.010..0.010 rows=1.00 loops=56987)
                     Cache Key: o.customer_id
                     Estimates: capacity=50174 distinct keys=50174 lookups=58044 hit percent=13.56%
                     Hits: 7423  Misses: 49564  Evictions: 0  Overflows: 0  Memory Usage: 5809kB

It keeps the result of each lookup by customer_id; an order whose customer was already looked up is answered from memory. 56,987 orders came from 49,564 customers, so 7,423 lookups were saved. The Estimates: line is the planner’s guess from n_distinct (hit percent=13.56%); Hits: is what happened (13.0%). Memoize is chosen only when the planner expects repeats: one more decision taken from an estimate.

Common misunderstandings

  • “ANALYZE runs the query.” ANALYZE orders collects statistics; EXPLAIN ANALYZE runs a query.
  • “More work_mem for everyone fixes spills.” Every Sort and hash node of every query on every connection may use that much: 100 connections × 3 nodes × 64 MB is 19,200 MB, and hash nodes up to twice that. Raise it for the query that needs it.

Check yourself

1. A Nested Loop's outer side shows rows=1 estimated and rows=40000.00 actual; the inner Index Scan has loops=40000. What happened, and what do you try first? A Nested Loop chosen for one row ran 40,000 lookups. Find why the estimate is wrong: statistics older than the data (run ANALYZE), an expression with no statistics, or correlated conditions.
2. A plan shows Filter: (date_trunc('day', created_at) = '2026-10-01') with rows=10000 on a 2,000,000-row table. Where does 10,000 come from? The fixed 0.5% guess for an expression without statistics: 2,000,000 × 0.005. Fix it with CREATE STATISTICS ... ON (date_trunc('day', created_at)) and ANALYZE, or rewrite the condition on the column (created_at >= '2026-10-01' AND created_at < '2026-10-02').
3. A nightly report shows Sort Method: external merge Disk: 120000kB. Name two ways to fix it. Give that report's session more memory (SET work_mem = '256MB'; before it runs), or avoid the sort: an index that already returns the rows in that order, or fewer rows to sort.

Next: Practical 2 · When the planner guesses wrong, then lesson 5 · In production.

5 · In production

In one sentence: on a running database you first find the query that costs the most time in total (pg_stat_statements), take real values for it from the slow-query log, then read its plan twice and compare like with like: the cache, the plan a prepared statement uses, and what EXPLAIN ANALYZE changes all differ from a quiet test.

The problem

So far the lessons gave you the slow query. In a running app, thousands of queries go by each minute and someone says “the shop is slow”. To find the one worth fixing, Postgres has to keep score.

Which queries take the time: pg_stat_statements

pg_stat_statements is an extension that ships with Postgres. It is loaded when the server starts (shared_preload_libraries) and then counts every statement (pg_stat_statements). Practical 3 sets it up.

Here pgbench, a load tool that ships with Postgres, played an app for 30 seconds: 4 connections running three queries over and over: a My orders page, Practical 2’s packing screen and lesson 2’s revenue report.

SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time::numeric, 1) AS mean_ms,
       left(query, 50) AS query
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5;
 calls | total_ms | mean_ms |                       query                        
-------+----------+---------+----------------------------------------------------
   249 |    73801 |   296.4 | SELECT c.country, count(*) AS orders, sum(o.total_
 12457 |    21848 |     1.8 | SELECT id, status, total_cents, created_at FROM or
  1086 |     5377 |     5.0 | SELECT o.id, o.created_at, c.email FROM orders o J
ColumnMeans
callshow many times it ran
total_exec_timemilliseconds spent running it, all calls together
mean_exec_timethe average per call

Sort by total time: it is where the server’s time goes. The revenue report is first. My orders is second at 1.8 ms a call, because it ran 12,457 times.

Each line stands for one query shape: constants become $1, $2. The revenue report is stored as WHERE o.created_at >= $1 AND o.created_at < $2. To run EXPLAIN you need real values.

Real values: the slow-query log

log_min_duration_statement logs every statement that took longer than the setting, as it was sent (Error Reporting and Logging). With 250ms, in docker logs:

2026-11-24 16:26:39.639 UTC [1079] LOG:  duration: 314.983 ms  statement: SELECT c.country, count(*) AS orders, sum(o.total_cents) AS revenue_cents
	FROM orders o JOIN customers c ON c.id = o.customer_id
	WHERE o.created_at >= '2026-10-01' AND o.created_at < '2026-11-01'

Paste that statement after EXPLAIN (ANALYZE, BUFFERS).

The plan as it ran: auto_explain

You run EXPLAIN later, on a quieter server. auto_explain logs the plan of the slow run itself, at the moment it was slow (auto_explain). For every new connection:

ALTER SYSTEM SET session_preload_libraries = 'auto_explain';
ALTER SYSTEM SET auto_explain.log_min_duration = '250ms';
ALTER SYSTEM SET auto_explain.log_analyze = on;
ALTER SYSTEM SET auto_explain.log_buffers = on;
SELECT pg_reload_conf();
2026-11-24 16:27:07.861 UTC [1257] LOG:  duration: 257.056 ms  plan:
	Query Text: SELECT c.country, count(*) AS orders, sum(o.total_cents) AS revenue_cents
...
	Sort  (cost=26326.06..26326.08 rows=8 width=19) (actual time=247.870..257.024 rows=8.00 loops=1)

log_analyze measures every statement, not only the slow ones; the documentation warns that this can slow a busy server a lot. Turn it on to catch a problem, then off (before Practical 3, whose numbers were measured without it):

ALTER SYSTEM RESET session_preload_libraries;
ALTER SYSTEM RESET auto_explain.log_min_duration;
ALTER SYSTEM RESET auto_explain.log_analyze;
ALTER SYSTEM RESET auto_explain.log_buffers;
SELECT pg_reload_conf();

Measure like with like: the cache

Lesson 1 said to run twice. Two queries, each run twice right after a server restart (Postgres’s cache empty): My orders for customer 4242, a few pages, and the sum of all total_cents, all 17,162 pages of orders. In some rounds the operating system’s cache of the database files was emptied too, so the first run read from the USB SSD. SET track_io_timing = on; adds the time spent waiting for reads. Three rounds each:

Runcustomer 4242sum of all orders
first, pages from the SSD3.0–3.3 ms568–586 ms
first, pages from the operating system’s cache0.82–0.85 ms307–345 ms
second0.13–0.15 ms310–353 ms
   Buffers: shared hit=7 read=17155
   I/O Timings: shared read=539.696

That was the full scan from the SSD: 540 ms waiting for reads, for the three processes together. From the operating system’s cache, the same read=17155 waited 14–24 ms. read= means “not in Postgres’s cache”, not “from disk”: I/O Timings tells you which.

Customer 4242’s second run found every page in Postgres’s cache (hit= only). The full scan’s second run read all its pages again from the operating system’s cache: a table this big doesn’t stay in Postgres’s 128 MB cache.

Prepared statements: one plan for every value

Some database libraries prepare a query once, then run it with different values. After five runs Postgres may switch to a generic plan, made without looking at the value (the plans before it are custom plans, made for the value given) (PREPARE):

PREPARE by_status(text) AS SELECT count(*), sum(total_cents) FROM orders WHERE status = $1;

After five EXECUTE by_status('delivered');, the next runs, for the 211 pending orders:

               ->  Parallel Seq Scan on orders  (cost=0.00..27578.67 rows=208333 width=4) (actual time=190.239..195.110 rows=70.33 loops=3)
                     Filter: (status = $1)
...
 Execution Time: 213.498 ms

$1 in a plan means a generic plan: built for a quarter of the table (4 values; 208,333 per process × 2.4 = 500,000 rows), whatever you asked. With SET plan_cache_mode = force_custom_plan; the same EXECUTE used the index: 0.38–0.41 ms instead of 213–220 ms.

A checklist

 1  find     pg_stat_statements, by total_exec_time (and by mean for one slow page)
 2  values   the slow-query log: the statement as it was sent
 3  read     EXPLAIN (ANALYZE, BUFFERS), twice; BEGIN ... ROLLBACK around writes
 4  where    the node with the most time of its own (lesson 2)
 5  why      the condition and the index (lesson 3); rows= against actual rows (lesson 4)
 6  fix      one change; then measure again, the same way, warm against warm

Try it on your computer

Practical 3 · Capstone: slow-query hunt: an app you’re given runs against your database; you find its slowest queries, fix them and write down the numbers.

Go deeper: when the generic plan wins

For its first five runs a prepared statement gets a custom plan, made for the values given. From then on Postgres compares the generic plan’s estimated cost with the average cost of the custom plans so far, and takes the generic one unless it costs clearly more (PREPARE, Notes). Five 'delivered' runs were priced at 32,327 each, the generic plan at 29,621, so the sixth run used the generic plan.

One cheap run among the five is enough. In another session one of them was for 'pending' (an Index Scan, cost 1,217): the average of the five was 26,105, below the generic plan’s cost, and all eight runs got custom plans (generic_plans 0, custom_plans 8 in pg_prepared_statements). Which plan a prepared statement uses depends on the values it has seen.

Common misunderstandings

  • “The plan EXPLAIN shows me is the plan the app ran.” The app’s run may have used a generic plan, had a colder cache or shared a busy server. The plan auto_explain logged is the one that ran.

Check yourself

1. pg_stat_statements shows a query with calls 900000, mean_ms 0.4, and another with calls 12, mean_ms 3000. Which costs the server more? The first: 900,000 × 0.4 = 360,000 ms, against 12 × 3,000 = 36,000 ms. The second may still be worth fixing for the person who waits 3 seconds, but it isn't where the server's time goes.
2. A plan from your app's log shows Filter: (customer_id = $1) and a Seq Scan, but your EXPLAIN ANALYZE with a real value shows an Index Scan. Why? $1 means the app's run used a generic plan, made without the value. Your EXPLAIN with a literal got a custom plan. Reproduce it with PREPARE and six EXECUTEs, or try plan_cache_mode = force_custom_plan for that app's connections.
3. A query took 2.1 s in the log, but 90 ms when you ran EXPLAIN (ANALYZE, BUFFERS). Name two things to compare. The cache: your run may find in memory pages the app's run had to read (read=, and I/O Timings with track_io_timing). And the plan: compare yours with the one auto_explain logged; it may be a generic plan, or the server may have been busy then.

Next: Practical 3 · Capstone: slow-query hunt.

Practical 0 · Your Postgres

Goal: Postgres 19 running in Docker with the shop from lesson 1 loaded, the plans from lesson 1 on your own screen, and proof that EXPLAIN ANALYZE really runs the statement you give it.

Time: ~20 minutes. Where: a terminal on your computer, in ~/pg-explain/. Needs Docker, curl and python3 (the lab script is a Python 3 program). Read lesson 1 first.

Task 1 · Get the lab

Create the workspace and download this course’s lab script into it:

mkdir -p ~/pg-explain
cd ~/pg-explain
curl -fo lab http://localhost:8800/pg-explain-in-depth/tools/lab
chmod +x lab
./lab setup p0

It prints one line per step:

  starting Postgres 19.0 (a few seconds; longer the first time, while Docker downloads postgres:19.0)…
  ✓ Postgres 19.0 in a container named explain-db, data in the volume explain-data (5 s)
  loading shop data from sql/shop.sql (about a minute)…
  ✓ shop data loaded: 200,000 customers, 2,000,000 orders (65 s)

ready for p0. psql in the container:  docker exec -it explain-db psql -U postgres -d shop
(every command is in lab.log; ./lab setup p0 -v shows them as they run)

The shop’s rows come from a fixed random seed, so yours are the ones in the lessons.

What setup did

It started Postgres 19 in a container named explain-db, keeping the database in a Docker volume named explain-data. It mounted your ~/pg-explain/sql folder at /sql inside the container, downloaded shop.sql into it and loaded it into a database named shop. Read sql/shop.sql: it’s under 50 lines.

It created the volume and the container with two commands (with your own home folder in the second -v):

docker volume create --label fromzero.course=pg-explain-in-depth explain-data
docker run -d --name explain-db --label fromzero.course=pg-explain-in-depth \
  -e POSTGRES_PASSWORD=explain -e POSTGRES_DB=shop \
  -v explain-data:/var/lib/postgresql \
  -v "$HOME/pg-explain/sql:/sql" \
  postgres:19.0
PieceWhy
-d --name explain-dbruns in the background, under a name the other commands use
--label fromzero.course=...marks the container and the volume as this course’s: ./lab reset removes only what has it, never a container of yours with the same name
POSTGRES_PASSWORD, POSTGRES_DB=shopthe superuser’s password, and a database shop made on the first start, when the volume is empty
-v explain-data:/var/lib/postgresqla source that is a plain name is a named volume: the database files survive docker rm explain-db
-v "$HOME/pg-explain/sql:/sql"a source that is a path is a folder on your computer: psql inside the container reads /sql/shop.sql from it
no -pno published port: everything in this course goes through docker exec

On the first start the image creates the database with a temporary server that listens only inside the container, then restarts Postgres for real. Setup waits with pg_isready -h 127.0.0.1, which only answers once the real server listens on the network.

Why /var/lib/postgresql, not /var/lib/postgresql/data:

Most guides written before Postgres 18 mount the volume at /var/lib/postgresql/data. The 18 and newer images keep their data in a version-named folder under /var/lib/postgresql instead, so one volume can hold two versions during an upgrade. With the old path, postgres:19.0 refuses to start:

Error: in 18+, these Docker images are configured to store database data in a
       format which is compatible with "pg_ctlcluster" (specifically, using
       major-version-specific directory names).  This better reflects how
...
       The suggested container configuration for 18+ is to place a single mount
       at /var/lib/postgresql which will then place PostgreSQL data in a
       subdirectory, allowing usage of "pg_upgrade --link" without mount point
       boundary issues.

(the change). That’s why setup mounts the volume where it does.

Run ./lab setup p0 again and it keeps everything you have (the container, the data, your files): setup never redoes a task of yours. If a step fails, setup prints that command and the last lines of its output; fix what it says and run the same ./lab command again.

Now open a psql session inside the container. You’ll use this command in every practical, and type the SQL of the rest of this one at its shop=# prompt (\q leaves):

docker exec -it explain-db psql -U postgres -d shop
PieceWhy
docker exec -it explain-dbrun a command inside the container, connected to your terminal
psql -U postgres -d shopPostgres’s own client, as the superuser postgres, in the database shop
\dt+
 public | customers | table | postgres | permanent   | heap          | 15 MB  | 
 public | orders    | table | postgres | permanent   | heap          | 130 MB | 

Task 2 · Your first plans

Run the lesson 1 query three ways and compare with the lesson: plain EXPLAIN, then EXPLAIN ANALYZE twice.

EXPLAIN SELECT * FROM orders WHERE customer_id = 4242;
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 4242;
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 4242;

Running it twice shows what changes between runs: the time a little, and how the pages split between hit and read. In the last run, find these and write them down:

  1. the node that reads the table, and its Rows Removed by Filter and loops
  2. the Buffers line: hit + read is the number of pages touched
  3. Execution Time
What you should see

A Parallel Seq Scan on orders under a Gather, loops=3, about 666,664 rows removed per loop, and hit + read = 16,667: every page, whatever the split. The time depends on your computer; it was 148 ms on a Raspberry Pi 4. You may also see a written= count on the Buffers line; lesson 2 explains it.

Predict first: customer 4242’s 7 rows are on 7 different pages. With an index on customer_id, will the query touch more than 7 pages, exactly 7, or fewer? Why?

Create the index from lesson 1 and look again:

CREATE INDEX orders_customer_id_idx ON orders (customer_id);
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 4242;

The table node is now a Bitmap Heap Scan fed by a Bitmap Index Scan on orders_customer_id_idx, with Heap Blocks: exact=7. On the top Buffers line, hit + read = 13 (on a fresh load: hit=10 read=3): 7 table pages plus 6 index pages (hit + read on the Buffers line under the index node). Looking something up in an index costs pages too.

Task 3 · Break it: EXPLAIN ANALYZE runs the statement

Predict first: you run EXPLAIN ANALYZE DELETE FROM orders WHERE customer_id = 4242;. Do customer 4242’s orders still exist afterwards?

Find out safely, inside a transaction you then undo:

BEGIN;
EXPLAIN ANALYZE DELETE FROM orders WHERE customer_id = 4242;
SELECT count(*) FROM orders WHERE customer_id = 4242;
ROLLBACK;
SELECT count(*) FROM orders WHERE customer_id = 4242;
 Delete on orders  (cost=4.51..47.80 rows=0 width=0) (actual time=0.541..0.548 rows=0.00 loops=1)
   Buffers: shared hit=24 dirtied=1
...
 count 
-------
     0
(1 row)

ROLLBACK
 count 
-------
     7
(1 row)

The proof is the count: 0 inside the transaction, so the rows were deleted. ANALYZE means “run it and measure it”, and it does that to an UPDATE or DELETE too. Only the ROLLBACK brought them back.

Don’t look for proof on the Buffers line: dirtied= counts only pages that had no unsaved changes yet, and a count of 0 isn’t printed (EXPLAIN, BUFFERS). Right after loading the shop, many pages still hold unsaved changes, so you may see a small dirtied= count or none at all.

Plain EXPLAIN DELETE ... (no ANALYZE) shows the plan with no actual numbers and deletes nothing: try it, then count again (still 7).

If the count is 0 after all (you ran it outside BEGIN), \q and run ./lab reset p1: it asks, removes the container and its volume, loads the shop again and recreates the index from task 2, as at the end of this practical. It took about 1¼ minutes on the Raspberry Pi 4, most of it loading the shop.

Check your work

Back in your terminal (\q):

./lab check p0

All 11 checks should pass. The checker only reads: it looks at your container, the data, the index and the plan.

Next: lesson 2 · Reading a plan.

Practical 1 · Where the time goes

Goal: “the 20 newest pending orders” made over a thousand times faster: you find the node that costs the time, try an index that helps a little, then the one that helps completely, and break it with one function call.

Time: ~30 minutes. Where: psql in your explain-db container (docker exec -it explain-db psql -U postgres -d shop), and ~/pg-explain/ for the lab script. Read lesson 2 first.

Skipped a practical, or your lab is in a state you don’t trust? ./lab reset p1 starts you here with the earlier practicals’ solutions in place. It takes about 1¼ minutes on a Raspberry Pi 4, most of it loading the shop.

The shop’s warehouse screen shows the 20 newest orders still waiting to ship:

SELECT id, customer_id, created_at, total_cents FROM orders
WHERE status = 'pending' ORDER BY created_at DESC LIMIT 20;

Task 1 · Find the node

Predict first: the plan will have a Limit, a Gather Merge, a Sort and a scan of orders. Which one takes most of the time?

In psql, run EXPLAIN ANALYZE on the query twice, and work on the second run. Using lesson 2’s method, write down for each node its last-row time and its own time, then answer: which node is the problem, and which of its lines says why?

Hint

The scan and the Sort have loops=3: they ran in 3 processes at the same time (lesson 1, Go deeper), so their times are per process and you compare them as they are. The Sort’s own time is its last-row time minus the scan’s.

What the second run showed on the Raspberry Pi 4
 Limit  (cost=28771.10..28773.43 rows=20 width=28) (actual time=192.488..204.160 rows=20.00 loops=1)
   ->  Gather Merge  (cost=28771.10..35991.90 rows=61999 width=28) (actual time=192.483..204.149 rows=20.00 loops=1)
         ->  Sort  (cost=27771.07..27835.66 rows=25833 width=28) (actual time=182.495..182.499 rows=15.33 loops=3)
               Sort Key: created_at DESC
               Sort Method: top-N heapsort  Memory: 27kB
               ->  Parallel Seq Scan on orders  (cost=0.00..27083.67 rows=25833 width=28) (actual time=0.486..170.149 rows=19868.67 loops=3)
                     Filter: (status = 'pending'::text)
                     Rows Removed by Filter: 646798
...
 Execution Time: 204.239 ms

The Parallel Seq Scan: 170 of 204 ms. Rows Removed by Filter: 646798 per process says why: it goes through every order to find the pending ones. The Sort (12 ms of its own) keeps the 20 newest per process, and the Gather Merge (22 ms of its own) merges the three processes’ rows.

Task 2 · An index on status

The filter is on status, so an index on status looks like the fix.

Predict first: 59,606 orders are pending. With an index on status, how much faster will the query be?

Create orders_status_idx on orders (status), then run EXPLAIN ANALYZE twice again.

Solution and what it showed
CREATE INDEX orders_status_idx ON orders (status);

The first run took 274 ms, with 13,103 pages from outside Postgres’s cache against 2,219 on the next run; the second run took 113.8 ms. The scan became a Parallel Bitmap Heap Scan fed by:

                     ->  Bitmap Index Scan on orders_status_idx  (cost=0.00..681.43 rows=62000 width=0) (actual time=17.709..17.709 rows=59606.00 loops=1)

rows=59606.00: the index finds every pending order, the scan fetches all of them from the table, and the Sort still sorts them all to keep 20. Better, not solved.

Task 3 · The right index

The query needs the pending orders in created_at order, and only 20 of them. Requirements:

  • drop orders_status_idx (it’ll be useless next to the new one)
  • create orders_status_created_at_idx: one index that holds the pending orders sorted by created_at
  • run EXPLAIN ANALYZE twice
Hint

An index on two columns, (a, b), is sorted by a, and inside each value of a by b. Which column goes first?

Solution
DROP INDEX orders_status_idx;
CREATE INDEX orders_status_created_at_idx ON orders (status, created_at);
 Limit  (cost=0.43..14.73 rows=20 width=28) (actual time=0.062..0.092 rows=20.00 loops=1)
   Buffers: shared hit=10
   ->  Index Scan Backward using orders_status_created_at_idx on orders  (cost=0.43..44335.24 rows=62000 width=28) (actual time=0.060..0.084 rows=20.00 loops=1)
         Index Cond: (status = 'pending'::text)
...
 Execution Time: 0.133 ms

0.133 ms, against 204 ms: over 1,500 times faster. Three things changed, and the plan shows each:

In the planMeans
no Sort nodethe index hands over the pending orders already in created_at order
Backwardit reads them from the newest end, as DESC asks
rows=20.00 on the scanLimit stopped it after 20 rows: 10 pages touched

Task 4 · Break it: one function call

A colleague makes the screen “case-insensitive” by changing the condition to lower(status) = 'pending'.

Predict first: the index is still there. Will the query use it?

Run the changed query with EXPLAIN ANALYZE, twice.

               ->  Parallel Seq Scan on orders  (cost=0.00..29167.00 rows=4167 width=28) (actual time=0.190..778.771 rows=19868.67 loops=3)
                     Filter: (lower(status) = 'pending'::text)
...
 Execution Time: 815.506 ms

815 ms: slower even than with no index at all (204 ms). Find out what happened, in this order:

  1. The scan node: Parallel Seq Scan, not Index Scan. The index wasn’t used.
  2. The Filter line: the condition is on lower(status). The index stores status; it has no idea what lower(status) is for each row, so it can’t find the matches.
  3. The estimate: rows=4167 per process, against rows=25833 before (yours may differ a little: ANALYZE reads a random sample of the table). The planner can’t estimate lower(status) either, so it falls back on a guess. Lesson 4 is about guesses like this one.

The scan touched the same 16,667 pages (every page of the table) and removed the same 646,798 rows per process as in Task 1; the only change in the plan is the Filter, which now computes lower(status) for every row. The data is already lowercase, so the fix is to compare the column itself: put status = 'pending' back and check that the plan shows the Index Scan Backward again.

Check your work

./lab check p1

All 9 checks should pass: the (status, created_at) index exists, orders_status_idx is gone, the query comes straight from the index with no Sort, and it returns the right 20 rows.

Go deeper: when the function has to stay

If the column really held mixed case, you’d index the expression itself:

CREATE INDEX orders_lower_status_created_at_idx ON orders (lower(status), created_at);

With it, the lower(status) query used Index Scan Backward using orders_lower_status_created_at_idx and took 0.203 ms. An expression index is only used for that exact expression, and it’s one more index to keep up to date on every write. If you try it, drop it afterwards (DROP INDEX orders_lower_status_created_at_idx;): nothing in this course needs it.

Next: lesson 3 · How rows are found.

Practical 2 · When the planner guesses wrong

Goal: three slow queries where the planner’s row estimate is the clue: one where old statistics make it build the wrong plan, one where two related columns fool it, and one where it plans around too little memory. For each, you compare rows= with the actual rows, give the planner what it lacks, and measure.

Time: ~40 minutes. Where: psql in your explain-db container (docker exec -it explain-db psql -U postgres -d shop), and ~/pg-explain/ for the lab script. Read lesson 4 first.

This practical’s ./lab setup p2 comes at the start of task 2, where it gives every customer a city: don’t run it before task 1.

Skipped a practical, or your lab is in a state you don’t trust? ./lab reset p2 starts you here with the earlier practicals’ solutions in place. It takes about 1½ minutes on a Raspberry Pi 4, most of it loading the shop.

In every task, run each EXPLAIN ANALYZE twice and work on the second run. The planner’s estimates (rows=) come from ANALYZE, which reads a random sample of the table, so yours may differ a little from the ones below.

Task 1 · A backlog the statistics haven’t seen

The warehouse has cleared its backlog: every pending order from before 20 December 2026 is shipped. In psql:

UPDATE orders SET status = 'shipped' WHERE status = 'pending' AND created_at < '2026-12-20';
UPDATE 59395

211 orders are still pending. The packing screen lists them with the customer’s email:

SELECT o.id, o.created_at, c.email FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending';

Predict first: how many pending orders will the planner expect? Which join method suits 211 rows?

Run EXPLAIN ANALYZE on it. Find the estimate that’s wrong, the join it led to, and the line that shows the index still knows about the old pending orders.

What the second run showed on the Raspberry Pi 4
 Hash Join  (cost=20335.82..28047.16 rows=60134 width=38) (actual time=490.564..601.797 rows=211.00 loops=1)
   ->  Seq Scan on customers c  (cost=0.00..3860.00 rows=200000 width=30) (actual time=0.039..46.701 rows=200000.00 loops=1)
   ->  Hash  (cost=19584.14..19584.14 rows=60134 width=24) (actual time=487.683..487.688 rows=211.00 loops=1)
         ->  Bitmap Heap Scan on orders o  (cost=1670.47..19584.14 rows=60134 width=24) (actual time=487.361..487.537 rows=211.00 loops=1)
               Heap Blocks: exact=16187
               ->  Bitmap Index Scan on orders_status_created_at_idx  (cost=0.00..1655.43 rows=60134 width=0) (actual time=30.465..30.466 rows=59606.00 loops=1)
...
 Execution Time: 602.690 ms
LineSays
rows=60134 against rows=211.00the planner still thinks about 3% of orders are pending: the statistics are from before the UPDATE
Hash Join over all 200,000 customersthe method for tens of thousands of rows
Bitmap Index Scan ... rows=59606.00the index still lists the old versions of the shipped orders; the scan visits 16,187 pages to check them and keeps 211 rows

Why hasn’t autovacuum caught up? Ask Postgres:

SELECT n_mod_since_analyze, last_autoanalyze FROM pg_stat_user_tables WHERE relname = 'orders';
               59395 | 

59,395 rows changed, and no automatic ANALYZE yet. Autovacuum analyzes a table once 50 rows + 10% of it have changed, 200,050 here, and vacuums it after 50 + 20% (autovacuum_analyze_scale_factor, autovacuum_vacuum_scale_factor in Vacuuming). A change to 3% of a table can change a query’s answer completely and leave the statistics as they were.

An UPDATE doesn’t change a row in place: it writes a new version and leaves the old one, still listed in the index, until VACUUM removes it (Routine Vacuuming).

Requirement: make the planner see the table as it is now, with one command that refreshes the statistics and removes the old row versions; then run the query twice again.

Solution and what it showed
VACUUM ANALYZE orders;
 Nested Loop  (cost=0.85..4755.85 rows=533 width=38) (actual time=0.113..2.186 rows=211.00 loops=1)
   ->  Index Scan using orders_status_created_at_idx on orders o  (cost=0.43..1214.66 rows=533 width=24) (actual time=0.088..0.311 rows=211.00 loops=1)
   ->  Index Scan using customers_pkey on customers c  (cost=0.42..6.64 rows=1 width=30) (actual time=0.007..0.007 rows=1.00 loops=211)
...
 Execution Time: 2.272 ms

2.3 ms instead of 603 ms. ANALYZE took a new sample: 8 of its 30,000 rows were pending, and 8/30,000 of 2,000,000 is the rows=533 (other walk-throughs got 200 and 333: 3 or 5 pending rows in the sample). Not 211, but the right size, and the planner chose a Nested Loop with 211 lookups. VACUUM removed the old versions, so the index finds only the 211 live rows.

Task 2 · Two columns that go together

The marketing team wants revenue from customers in Berlin. Customers need a city first. In ~/pg-explain (\q first, or a second terminal):

./lab setup p2
  giving every customer a city with sql/cities.sql (a few seconds)…
  ✓ every customer has a city: 8,333 in Berlin (6 s)

ready for p2. psql in the container:  docker exec -it explain-db psql -U postgres -d shop
(every command is in lab.log; ./lab setup p2 -v shows them as they run)

Every country gets 3 cities, and cities.sql ends with VACUUM ANALYZE customers: the estimate below isn’t stale.

What setup did

It ran ~/pg-explain/sql/cities.sql (read it): a city column on customers, filled for all 200,000. Run again, it keeps your cities.

The query:

SELECT count(*), sum(o.total_cents) FROM customers c JOIN orders o ON o.customer_id = c.id
WHERE c.country = 'DE' AND c.city = 'Berlin';

Predict first: an eighth of customers are in DE, a twenty-fourth in Berlin. Multiplying them as lesson 4 says, how many Berlin customers will the planner expect?

Run EXPLAIN ANALYZE, and find the scan of customers.

What it showed
                     ->  Parallel Seq Scan on customers c  (cost=0.00..5224.00 rows=440 width=8) (actual time=15.562..53.405 rows=2777.67 loops=3)
                           Filter: ((country = 'DE'::text) AND (city = 'Berlin'::text))

440 per process (about 1,056 in all) against 2,777.67 × 3 = 8,333: 1/8 × 1/24 of 200,000 is 1,042. The planner doesn’t know that every Berlin customer is in DE. A Nested Loop with 8,333 lookups into orders took 402 ms.

CREATE STATISTICS can also record how far one column determines another (the kind dependencies): statistics on several columns together, called extended statistics.

Requirements:

  • create extended statistics named customers_country_city_stats, of the kind dependencies, on country and city of customers (CREATE STATISTICS)
  • run the query with EXPLAIN ANALYZE straight away, before anything else
  • then make the statistics count, and run it twice more
Solution
CREATE STATISTICS customers_country_city_stats (dependencies) ON country, city FROM customers;
ANALYZE customers;

Break it, built in: straight after CREATE STATISTICS, the scan still said rows=440, as lesson 4 said it would. After ANALYZE customers:

               ->  Parallel Hash Join  (cost=5266.36..32949.24 rows=33888 width=4) (actual time=23.553..443.468 rows=27784.67 loops=3)
...
                           ->  Parallel Seq Scan on customers c  (cost=0.00..5224.00 rows=3389 width=8) (actual time=0.962..21.190 rows=2777.67 loops=3)
...
 Execution Time: 477.105 ms

rows=3389 per process: about 8,133, right. And it was slower. With the right count, the planner priced the Nested Loop at 41,254 and chose a Hash Join priced at 34,119, which took 477–518 ms against the Nested Loop’s 392–402 ms. The planner’s costs are estimates too. A wrong estimate matters when it changes the plan for the worse, as in Task 1; the time tells you whether a fix helped.

Task 3 · A report planned around too little memory

The monthly report of the 10 best customers:

SELECT customer_id, sum(total_cents) AS spent FROM orders GROUP BY customer_id ORDER BY spent DESC LIMIT 10;

Run EXPLAIN ANALYZE. Which node takes the time, and how does it get the orders grouped by customer?

What it showed
         ->  GroupAggregate  (cost=0.43..119505.99 rows=178819 width=16) (actual time=0.175..7066.305 rows=199990.00 loops=1)
               Buffers: shared hit=1899819 read=101888
               ->  Index Scan using orders_customer_id_idx on orders  (cost=0.43..107717.80 rows=2000000 width=12) (actual time=0.131..6201.012 rows=2000000.00 loops=1)
...
 Execution Time: 7208.069 ms

7.2 s. To group, the plan reads all 2,000,000 orders through the customer_id index, so they come out customer by customer: 6.2 s of it in the Index Scan, 2,001,707 pages touched for a table of 17,162 (the Seq Scan below reads all of them). The table was 16,667 pages: task 1’s UPDATE wrote new versions of 59,395 rows, about 495 pages at ~120 rows a page, and VACUUM frees the old versions’ space for reuse but keeps the pages.

Predict first: a hash table of 178,819 customers’ sums needs more than 4 MB × 2. What will the plan be with SET work_mem = '64MB';?

Set it for your session, then run the query twice.

         ->  HashAggregate  (cost=47162.00..48950.19 rows=178819 width=16) (actual time=2169.001..2287.515 rows=199990.00 loops=1)
               Batches: 1  Memory Usage: 12313kB
               ->  Seq Scan on orders  (cost=0.00..37162.00 rows=2000000 width=12) (actual time=0.039..431.267 rows=2000000.00 loops=1)
...
 Execution Time: 2359.256 ms

2.3 s: one Seq Scan and a hash table of 12,313 kB, more than the 8 MB a hash could have at 4 MB.

Was memory what it lacked? In a new session, at 4 MB, with the index plan and parallel workers switched off for the test (SET enable_indexscan = off; SET max_parallel_workers_per_gather = 0;), the hash spilled to disk:

               Planned Partitions: 4  Batches: 5  Memory Usage: 8249kB  Disk Usage: 31744kB
...
 Execution Time: 3321.699 ms

The spill cost about 1 second (3.3 s against 2.3 s); the planner’s choice cost about 4 more (7.2 s). It priced the spilling hash at 190,471 and reading 2,000,000 rows through the index at 123,370, then took the cheaper-looking one. At 64 MB the hash plan was priced at 52,814, below the index plan, so the planner chose it. Raising work_mem is the fix here because it changes the prices.

Break it: leave psql (\q) and connect again. Run SHOW work_mem; and EXPLAIN on the query: 4MB, and the GroupAggregate is back. SET lasts for one session. For a report, set it in the report’s own session (or ALTER ROLE reports SET work_mem = '64MB'; for a role only reports use), not for the whole server: lesson 4’s 19,200 MB is what a server-wide 64 MB can add up to.

Check your work

./lab check p2

All 13 checks should pass: 211 pending orders, fresh statistics, no old row versions left and a Nested Loop for the packing screen, the cities and their extended statistics, and work_mem still 4 MB for everyone.

Next: lesson 5 · In production.

Practical 3 · Capstone: slow-query hunt

Goal: an app you’re given runs against your shop. Nobody tells you which query is slow: you make Postgres keep score, find the queries that cost the most, take them from the log, read their plans, fix them, and prove it with numbers in a report you write.

Time: ~60 minutes. Where: your terminal in ~/pg-explain/ and psql in explain-db (docker exec -it explain-db psql -U postgres -d shop). Read lesson 5 first.

./lab setup p3
  ✓ the app's 3 query files in sql/app/

ready for p3. psql in the container:  docker exec -it explain-db psql -U postgres -d shop
(every command is in lab.log; ./lab setup p3 -v shows them as they run)
What setup did

It downloaded login.sql, my-orders.sql and daily-report.sql into ~/pg-explain/sql/app/: the app you run in task 2. Your container and data stay as they are. Run it again and it keeps any of those files you already have, changes included (task 4 has you edit them); delete one first for a fresh copy.

Skipped a practical, or your lab is in a state you don’t trust? ./lab reset p3 starts you here with the earlier practicals’ solutions in place. It takes about 1¾ minutes on a Raspberry Pi 4, most of it loading the shop.

Task 1 · Let Postgres keep score

Predict first: in psql, run CREATE EXTENSION pg_stat_statements; and then SELECT count(*) FROM pg_stat_statements;. Will the count work?

CREATE EXTENSION
ERROR:  pg_stat_statements must be loaded via "shared_preload_libraries"

The extension’s tables exist, but nothing counts until the library is loaded when the server starts. Requirements:

  • the extension created in shop (the Predict first did it)
  • pg_stat_statements in shared_preload_libraries, set so that it survives a restart, then the container restarted; SELECT count(*) FROM pg_stat_statements; answers
  • every statement that takes longer than 250 ms written to the server log (no restart needed for this one)
Hint

ALTER SYSTEM SET name = 'value'; writes a setting to a file in the data directory, so it lives in your volume. shared_preload_libraries is read only at start: docker restart explain-db. The logging setting is log_min_duration_statement (lesson 5), and SELECT pg_reload_conf(); makes the server read it again.

Solution
ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements';

\q, then docker restart explain-db, connect again, and:

SELECT count(*) FROM pg_stat_statements;
ALTER SYSTEM SET log_min_duration_statement = '250ms';
SELECT pg_reload_conf();

Task 2 · Run the app

The app is three queries, each in a file in the format of pgbench, the load tool that ships with Postgres. ./lab setup p3 put them in ~/pg-explain/sql/app/. Read them: each has a comment saying what it is, a \set line that picks a random value, and the query that uses it. Then run the app for a minute:

docker exec explain-db pgbench -U postgres -n -c 4 -T 60 \
  -f /sql/app/login.sql@60 -f /sql/app/my-orders.sql@38 -f /sql/app/daily-report.sql@2 shop
PieceWhy
-ndon’t vacuum pgbench’s own tables first: there are none in shop
-c 4 -T 604 connections, each sending its next query as soon as the last one finishes, for 60 seconds
-f file@60run this file in 60% of the runs: logins are the most frequent
number of transactions actually processed: 963
tps = 15.982914 (without initial connection time)

A pgbench “transaction” here is one run of one file: one query. 963 in a minute, 16 a second, over 4 connections.

Predict first: which of the three takes the most time in total? Which has the highest mean?

In psql, list the top 5 by total time, then by mean, with lesson 5’s query.

What it showed
 calls | total_ms | mean_ms |                       query                        
-------+----------+---------+----------------------------------------------------
   568 |   218591 |   384.8 | SELECT id, country FROM customers WHERE lower(emai
    17 |    18682 |  1098.9 | SELECT status, count(*), sum(total_cents) FROM ord
   378 |     1404 |     3.7 | SELECT id, status, total_cents, created_at FROM or

The login takes the most time in total, the daily report the most per call (1.1 s, but only 17 calls). My orders is fast.

Create ~/pg-explain/report.md and write the “before” numbers in it: the runs per second, then one section per file, headed by its name (login.sql, daily-report.sql, my-orders.sql), with its calls and mean.

Task 3 · Find out why

Take each slow query from the log, as you would from a real app’s. Do it before your own EXPLAINs: anything over 250 ms is logged, yours too.

docker logs explain-db 2>&1 | grep duration | grep 'lower(email)' | tail -1
docker logs explain-db 2>&1 | grep duration | grep 'created_at::date' | tail -1
2026-11-24 16:38:43.411 UTC [58] LOG:  duration: 349.296 ms  statement: SELECT id, country FROM customers WHERE lower(email) = lower('User' || 22756 || '@Example.com');
2026-11-24 16:38:37.646 UTC [58] LOG:  duration: 1099.316 ms  statement: SELECT status, count(*), sum(total_cents) FROM orders WHERE created_at::date = date '2026-11-30' - 19 GROUP BY status;

Your values and times will differ. Run each statement twice in psql with EXPLAIN (ANALYZE, BUFFERS). For each, write in your report: the node with the most time of its own, the condition on it, and why no index serves that condition (lesson 3).

What it showed
   ->  Parallel Seq Scan on customers  (cost=0.00..5224.00 rows=417 width=11) (actual time=72.957..103.361 rows=0.33 loops=3)
         Filter: (lower(email) = 'user22756@example.com'::text)
         Rows Removed by Filter: 66666
...
 Execution Time: 118.578 ms
                     ->  Parallel Seq Scan on orders  (cost=0.00..29662.00 rows=4167 width=13) (actual time=371.531..393.528 rows=612.67 loops=3)
                           Filter: ((created_at)::date = '2026-11-11'::date)
                           Rows Removed by Filter: 666054
...
 Execution Time: 414.293 ms

Both read a whole table to keep a few rows, because the condition is on an expression, lower(email) and created_at::date, and no index stores either. The planner had already worked out lower('User' || 22756 ...) once: the Filter shows its result.

The daily report took 1,099 ms in the log and 414 ms here. In the app it ran alongside three other connections, most of them running the login’s full scan. The same slowed My orders: its query and index don’t change in task 4, yet its mean falls from 3.7 ms to 0.9 ms once the scans are gone (task 4’s list).

Task 4 · Fix them, and prove it

Requirements:

  • the login must not change: the app’s code can’t be released today. Make login.sql fast as it is
  • the daily report: you may change daily-report.sql, as long as it gives the same answer

Break it first: for the daily report, try an index on its expression:

CREATE INDEX ON orders ((created_at::date));
ERROR:  functions in index expression must be marked IMMUTABLE

An index stores the expression’s value once; the expression must give the same result every time. This one doesn’t:

SELECT id, created_at, created_at::date FROM orders WHERE id = 1920715;
SET TimeZone = 'Asia/Tokyo';
SELECT id, created_at, created_at::date FROM orders WHERE id = 1920715;
 1920715 | 2026-11-10 20:00:05+00 | 2026-11-10
...
 1920715 | 2026-11-11 05:00:05+09 | 2026-11-11

The same order belongs to 10 November in UTC and to 11 November in Tokyo. RESET TimeZone; afterwards.

Hint

The login: lesson 3’s Check yourself 1 has the same condition. The daily report: rewrite the condition on created_at itself, which an index already covers. “created_at::date is that day” means “created_at is from that day’s midnight up to, not including, the next day’s”. date '2026-11-30' - :d is a date; + 1 is the next day. Run the old and the new query for one day (replace :d with 23) and compare their rows.

Solution
CREATE INDEX customers_lower_email_idx ON customers (lower(email));

The query line of daily-report.sql, rewritten:

SELECT status, count(*), sum(total_cents) FROM orders WHERE created_at >= date '2026-11-30' - :d AND created_at < date '2026-11-30' - :d + 1 GROUP BY status;

Both versions for 23 gave the same three rows (cancelled 20, delivered 1663, shipped 155).

With EXPLAIN (ANALYZE, BUFFERS), the second of two runs each (the daily report for 7 November, - 23, both times; its “before” was measured later than task 3’s run, with more pages already in Postgres’s cache, so it differs from task 3’s 414 ms: compare runs made the same way):

QueryBeforeAfterPlan after
login (customer 22756)118.578 ms0.118 msBitmap Index Scan on customers_lower_email_idx
daily report347.168 ms2.361 msIndex Scan using orders_status_created_at_idx

Now the whole app. In psql, SELECT pg_stat_statements_reset(); empties the counts; then run the same pgbench command as in task 2, and list the top 5 again.

number of transactions actually processed: 168009
tps = 2801.289051 (without initial connection time)
 calls  | total_ms | mean_ms |                       query                        
--------+----------+---------+----------------------------------------------------
  63474 |    59141 |     0.9 | SELECT id, status, total_cents, created_at FROM or
 101167 |    16866 |     0.2 | SELECT id, country FROM customers WHERE lower(emai
   3368 |     7837 |     2.3 | SELECT status, count(*), sum(total_cents) FROM ord

2,801 runs a second instead of 16. A second walk-through on the same Pi gave 15 and 3,512: these counts vary from run to run, so compare your own before and after, not yours with these. My orders is now first by total time, at 0.9 ms a call: a top list always has a top. Stop when each line is fast for what it does.

Finish your report: for login.sql and daily-report.sql, the mean before and after, the fix, and the runs per second before and after.

Check your work

./lab check p3

All 14 checks should pass. The checker reruns your login.sql and daily-report.sql with fixed values, compares the daily report’s answer with the original query’s for three days, and reads your report.

You can now do what this course set out to: take a slow query from the logs, run EXPLAIN ANALYZE on it, and say why it’s slow and what would fix it. To remove everything this course made: docker rm -f explain-db && docker volume rm explain-data && rm -rf ~/pg-explain.

Next: back to the front page, or lesson 5’s checklist.