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-dbcontainer (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, aGather Merge, aSortand a scan oforders. 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 bycreated_at - run
EXPLAIN ANALYZEtwice
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 plan | Means |
|---|---|
no Sort node | the index hands over the pending orders already in created_at order |
Backward | it reads them from the newest end, as DESC asks |
rows=20.00 on the scan | Limit 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:
- The scan node:
Parallel Seq Scan, notIndex Scan. The index wasn’t used. - The Filter line: the condition is on
lower(status). The index storesstatus; it has no idea whatlower(status)is for each row, so it can’t find the matches. - The estimate:
rows=4167per process, againstrows=25833before (yours may differ a little:ANALYZEreads a random sample of the table). The planner can’t estimatelower(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.