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

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.