Partitionwise Join Pairs Up Partitions
enable_partitionwise_join lets the planner pair up partitions and join per partition when both tables are partitioned on the join key.
Code
-- 两表按同一分区键、相同分区界线分区,且 join 条件含分区键时,
-- partitionwise join 逐分区配对做小 join 再 Append(默认关闭)
CREATE TABLE orders_p (customer_id int, total_cents int) PARTITION BY RANGE (customer_id);
CREATE TABLE customers_p (id int, region text) PARTITION BY RANGE (id);
CREATE TABLE orders_p_1 PARTITION OF orders_p FOR VALUES FROM (0) TO (100);
CREATE TABLE orders_p_2 PARTITION OF orders_p FOR VALUES FROM (100) TO (200);
CREATE TABLE customers_p_1 PARTITION OF customers_p FOR VALUES FROM (0) TO (100);
CREATE TABLE customers_p_2 PARTITION OF customers_p FOR VALUES FROM (100) TO (200);
INSERT INTO orders_p SELECT g % 200, 1000 FROM generate_series(1, 2000) g;
INSERT INTO customers_p SELECT g, 'r' FROM generate_series(0, 199) g;
ANALYZE orders_p, customers_p;
-- 关闭:一个大 join,两侧各是分区 Append
SET enable_partitionwise_join = off;
EXPLAIN (COSTS OFF)
SELECT c.region, SUM(o.total_cents)
FROM orders_p o JOIN customers_p c ON c.id = o.customer_id
GROUP BY c.region;
-- 开启:Append 里逐分区配对,每个小 join 只碰同一分区界线内的行
SET enable_partitionwise_join = on;
EXPLAIN (COSTS OFF)
SELECT c.region, SUM(o.total_cents)
FROM orders_p o JOIN customers_p c ON c.id = o.customer_id
GROUP BY c.region;The setup
Both tables are range-partitioned on the join key with identical bounds: orders_p on customer_id and customers_p on id, each split at 0/100/200, and both are ANALYZEd so the planner has statistics.
Off versus on
With enable_partitionwise_join = off, EXPLAIN shows one large join whose two sides are Append plans over all partitions. With it on, the Append moves outside: each small partition pair joins independently and the results append — every small join only touches rows inside one partition bound.
When the planner can pair partitions
Three conditions: both tables partitioned, on the same key with matching bounds, and the join condition contains the partition key. The demo satisfies all three; the setting is off by default because per-partition planning costs planning time.
Interactive Tools for This Topic
FAQ
- What must be true for partitionwise join to apply?
- Both tables must be partitioned on the join key with matching bounds, and the join condition must include the partition key.
- Why is enable_partitionwise_join off by default?
- Pairing partitions adds planning overhead; it pays off when partitions are large and per-partition joins filter substantially.
Report a problem with this exampleOpens a pre-filled issue on GitHub.