Part 18 / Topic 6 of 7
Parallel query
Big enough work gets split across CPU cores. Two million rows to aggregate:
CREATE TABLE big_events AS
SELECT g AS id, (g % 100) + 1 AS sensor, random() * 100 AS value
FROM generate_series(1, 2000000) AS g;
ANALYZE big_events;
EXPLAIN (COSTS OFF)
SELECT sensor, avg(value) FROM big_events GROUP BY sensor;
SELECT 2000000
ANALYZE
QUERY PLAN
---------------------------------------------------------
Finalize GroupAggregate
Group Key: sensor
-> Gather Merge
Workers Planned: 2
-> Sort
Sort Key: sensor
-> Partial HashAggregate
Group Key: sensor
-> Parallel Seq Scan on big_events
(9 rows)
Read it bottom-up, it's a little assembly line: Parallel Seq Scan (each worker reads its share of pages) → Partial HashAggregate (each worker aggregates its share) → Gather Merge under Workers Planned: 2 (the leader collects) → Finalize GroupAggregate (partial results combined). Parallelism kicks in for big scans, joins, and aggregations when the planner's cost math says the setup tax is worth it — governed by max_parallel_workers_per_gather (default 2) and the min_parallel_* size thresholds.
Two honest footnotes: writes (INSERT/UPDATE/DELETE) don't parallelize, and Workers Planned is a request — a busy server may launch fewer (Workers Launched in ANALYZE output tells the truth). Parallel query makes big analytical queries faster; it does nothing for the thousand tiny lookups OLTP lives on — those want indexes, not workers.
🧪 Quick quiz — answer from memory, then check.
- What do Partial and Finalize aggregate nodes mean?
- Why doesn't parallelism help point lookups?
Show the answers
- Each worker aggregated its slice (Partial); the leader merged the slices (Finalize).
- The setup cost outweighs microseconds of work — parallelism pays off on large scans, not index hits.
Done here? The practice set for Part 18 — 5 exercises with solutions — is on the part page.