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

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.