Part 18 / Stage 4
Query tuning
Goal: A repeatable method for slow queries — find the worst offenders with pg_stat_statements, write predicates indexes can serve, paginate at scale, kill N+1s, control CTE materialization, read parallel plans, and know the few settings worth touching first. Time: ~2.5 hours
What you will learn
- Finding slow queries:
pg_stat_statementsandlog_min_duration_statement - Index-friendly (sargable) predicates — the rewrites that unlock indexes
- Pagination at scale: keyset vs OFFSET
- The N+1 problem, and the
ANYbatch cure - CTE materialization: inlining,
MATERIALIZED/NOT MATERIALIZED - Parallel query: reading Gather plans
- Configuration: the first-look settings
The lab: the same 200k-row big_orders Part 16 used (each part stands alone, so build it fresh), plus — later — one 2-million-row table where size matters:
CREATE TABLE big_orders AS
SELECT g AS id, (g % 5000) + 1 AS customer_id,
DATE '2024-01-01' + (g % 365) AS order_date,
round((random() * 500)::numeric, 2) AS amount
FROM generate_series(1, 200000) AS g;
ALTER TABLE big_orders ADD PRIMARY KEY (id);
CREATE INDEX idx_big_orders_customer ON big_orders (customer_id);
CREATE INDEX idx_big_orders_date ON big_orders (order_date);
ANALYZE big_orders;
SELECT 200000
ALTER TABLE
CREATE INDEX
CREATE INDEX
ANALYZE
Topics in this part
Practice
SQL workbench — write and run queries here
Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.
Solutions build their own lab tables (run ex03 before ex04/ex05, which reuse its table). Exercise 1 needs pg_stat_statements in shared_preload_libraries.
Exercise 1: Read the meter
What to do: Reset pg_stat_statements, generate contrast traffic (one 2-million-row aggregate; SELECT 1 five times), then show the top queries by total time and by calls — and say which view would catch an N+1.
💡 Hint: pg_stat_statements_reset(), then two ORDER BYs over the view. The calls column is the N+1 detector.
Show the solution to Exercise 1
-- Exercise 1: Read the meter (needs pg_stat_statements preloaded)
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT pg_stat_statements_reset() IS NOT NULL AS reset_ok;
-- Generate traffic: one expensive statement, one cheap-but-chatty one.
SELECT count(*) FROM generate_series(1, 2000000);
SELECT 1; SELECT 1; SELECT 1; SELECT 1; SELECT 1;
-- Top by total time vs top by calls tell different stories:
SELECT calls, round(total_exec_time::numeric, 1) AS total_ms, left(query, 40) AS query
FROM pg_stat_statements
WHERE query NOT ILIKE '%pg_stat_statements%'
ORDER BY total_exec_time DESC LIMIT 2;
SELECT calls, round(total_exec_time::numeric, 1) AS total_ms, left(query, 40) AS query
FROM pg_stat_statements
WHERE query NOT ILIKE '%pg_stat_statements%'
ORDER BY calls DESC LIMIT 2;
Exercise 2: Sargable rewrites
What to do: Rewrite each so an index could serve it:
(a) WHERE extract(year FROM order_date) = 2024
(b) WHERE price * 1.18 > 100
(c) WHERE coalesce(cancelled_at, 'infinity') > now()
💡 Hint: bare column, constant-side math: a date range; divide the constant; split the NULL case out with OR (or a partial index).
Show the solution to Exercise 2
-- Exercise 2: Sargable rewrites — answers as before/after pairs.
-- (a) WHERE extract(year FROM order_date) = 2024
-- -> WHERE order_date >= DATE '2024-01-01' AND order_date < DATE '2025-01-01'
-- (b) WHERE price * 1.18 > 100
-- -> WHERE price > 100 / 1.18
-- (c) WHERE coalesce(cancelled_at, 'infinity') > now()
-- -> WHERE (cancelled_at IS NULL OR cancelled_at > now())
-- (or a partial index WHERE cancelled_at IS NULL for the hot case)
-- Proof of the pattern on big_orders (built in ex03 below / Part 18's lab):
SELECT 'rewrites - see comments' AS note;
Exercise 3: From OFFSET to keyset
What to do: On a 200k-row table ordered by (order_date, id): show the deep-page OFFSET plan fetching 100,020 rows for 20, then the keyset version with a composite row cursor fetching exactly 20.
Sample output (the contrast, from a real run):
Limit (actual rows=20 loops=1)
-> Index Scan using idx_big_orders_date_id on big_orders (actual rows=100020 loops=1)
Limit (actual rows=20 loops=1)
-> Index Scan using idx_big_orders_date_id on big_orders (actual rows=20 loops=1)
Index Cond: (ROW(order_date, id) > ROW('2024-06-29'::date, 100000))
💡 Hint: WHERE (order_date, id) > (DATE '...', 100000) ORDER BY order_date, id LIMIT 20 — row comparison syntax exists for exactly this.
Show the solution to Exercise 3
-- Exercise 3: From OFFSET to keyset (re-runnable)
DROP TABLE IF EXISTS big_orders;
CREATE TABLE big_orders AS
SELECT g AS id, (g % 5000) + 1 AS customer_id,
DATE '2024-01-01' + (g % 365) AS order_date,
round((random() * 500)::numeric, 2) AS amount
FROM generate_series(1, 200000) AS g;
ALTER TABLE big_orders ADD PRIMARY KEY (id);
CREATE INDEX idx_big_orders_date_id ON big_orders (order_date, id);
ANALYZE big_orders;
-- Before: page 5000 of a date-ordered listing, 20 per page.
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM big_orders ORDER BY order_date, id OFFSET 100000 LIMIT 20;
-- After: keyset with the composite cursor (last row's date + id).
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM big_orders
WHERE (order_date, id) > (DATE '2024-06-29', 100000)
ORDER BY order_date, id
LIMIT 20;
Exercise 4: Kill the N+1
What to do: The app fetched four orders in four round trips. Fetch ids 15, 2300, 77777 and 150000 in one statement that takes a single array parameter.
💡 Hint: WHERE id = ANY (ARRAY[...]) — in application code the array is one bind parameter, whatever its length.
Show the solution to Exercise 4
-- Exercise 4: Kill the N+1 (needs ex03's big_orders)
-- The loop the app was running 50 times:
-- SELECT * FROM big_orders WHERE id = $1;
-- The one-statement batch:
SELECT id, customer_id, amount
FROM big_orders
WHERE id = ANY (ARRAY[15, 2300, 77777, 150000])
ORDER BY id;
Exercise 5: The fence experiment
What to do: Write a CTE filtering June's orders, with an outer WHERE id = 150000. EXPLAIN it plain, then with AS MATERIALIZED — and narrate the difference in one sentence each.
Sample output (the shapes):
Index Scan using big_orders_pkey on big_orders
Index Cond: (id = 150000)
CTE Scan on june
Filter: (id = 150000)
CTE june
-> Seq Scan on big_orders
💡 Hint: inlined, the id filter reached the primary key; fenced, 80,000 buffered rows got scanned for one id.
Show the solution to Exercise 5
-- Exercise 5: The fence experiment (needs ex03's big_orders)
-- Inlined (default): the outer filter reaches the index inside the CTE.
EXPLAIN (COSTS OFF)
WITH june AS (SELECT * FROM big_orders WHERE order_date >= DATE '2024-06-01')
SELECT * FROM june WHERE id = 150000;
-- Fenced: the CTE computes alone; the id filter runs on the buffer.
EXPLAIN (COSTS OFF)
WITH june AS MATERIALIZED (SELECT * FROM big_orders WHERE order_date >= DATE '2024-06-01')
SELECT * FROM june WHERE id = 150000;
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Tuning the query someone complained about | The actual bill-payer runs on | pg_stat_statements by total_exec_time first |
| Functions wrapped around indexed columns | Indexes silently unused | Bare column; constant-side math; expression indexes |
| OFFSET for deep pagination | Each page slower than the last | Keyset with a unique cursor |
| "The query is fast" (× 400,000 calls) | N+1 invisible to per-query checks | Watch calls; join or ANY-batch |
| MATERIALIZED out of habit | Optimization fences everywhere | Default inlining; fence deliberately |
| Config-first tuning | Knobs can't fix un-sargable SQL | Queries and indexes first; the four settings once |
Quick recap
- Measure first, with pg_stat_statements (total versus mean time, plus call counts) and slow-query logging.
- Keep predicates sargable: nothing touches the column's side of the operator.
- Keyset pagination needs a cursor and a unique order; OFFSET is fine only while it stays shallow.
- An N+1 pattern shows up as a huge call count; fix it with a join or
= ANY(array). - CTEs inline since PG12; MATERIALIZED is a tool (cache/fence), not a default.
- A parallel plan reads Parallel scan, then Partial aggregate, then Gather, then Finalize — and it pays off for analytical queries only.
- Four first-look settings; after that, change one thing and re-measure.
Checklist
Before the Stage 4 project, make sure you can:
- Pull the top three queries by total time and by mean time, and say which you'd tune first.
- Spot and rewrite three un-sargable predicates on sight.
- Convert an OFFSET pagination to keyset, tiebreaker included.
- Diagnose an N+1 from pg_stat_statements alone.
- Predict a CTE's inlining and force it both ways.
- Read a parallel aggregate plan bottom-up.
Read more: the official pg_stat_statements page, parallel query chapter, and resource consumption settings.