skip to content

table partitioning

range, list and hash partitions, pruning at plan and run time, and the key every unique index must include.

address
everything.scale.partitioning
part
part 17, scale and distribution
chapter
chapter 3 of 10
reading time
8 min

a partitioned table is one table name over several real tables (partitions), split by a partition key: ranges of a date, lists of values, or a hash. queries that filter on the key skip partitions that can't match (partition pruning), at plan time or at run time, and old data leaves by detaching a partition instead of deleting rows. every unique index must include the key.

the picture

you know how a table of events grows forever, and the queries only ever look at last week, and deleting last year takes an afternoon and leaves bloat behind? partitioning is the filing cabinet answer: one drawer per month (a partition). you open the drawer for the month you want, and throwing out a year is pulling out twelve drawers.

here are the 25,000 events of the events dataset in three monthly partitions. pick a WHERE and see which drawers postgres opens:

WHERE =
  1. SELECT count(*) FROM ev WHERE occurred_at >= '2026-04-01' AND occurred_at < '2026-04-15'

a range inside april: the planner proves march and may can't match, and leaves them out of the plan.

readstarted, never executedpruned (struck)
real output, postgres 18.6 (PGlite 0.5.12) · pruning
one partitioned table, three partitions, five queries. every tile comes from that query's real plan: read, struck out (pruned before anything ran), or dashed (started but never executed). three different moments to skip a partition.

building one

the parent says how to split, each partition says which slice it holds. the parent has no storage of its own; rows go to whichever partition their key belongs to.

sqldb=events · session r
SET TimeZone = 'UTC';
CREATE TABLE ev (
  id          bigint NOT NULL,
  user_id     int NOT NULL,
  kind        text NOT NULL,
  occurred_at timestamptz NOT NULL,
  amount      numeric(10,2)
) PARTITION BY RANGE (occurred_at);
 
CREATE TABLE ev_2026_03 PARTITION OF ev FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');
CREATE TABLE ev_2026_04 PARTITION OF ev FOR VALUES FROM ('2026-04-01') TO ('2026-05-01');
CREATE TABLE ev_2026_05 PARTITION OF ev FOR VALUES FROM ('2026-05-01') TO ('2026-06-01');
 
INSERT INTO ev SELECT id, user_id, kind, occurred_at, amount FROM events ORDER BY id;
ANALYZE ev;
output, from postgres 18.6
#1 · SET
#2 · CREATE TABLE
#3 · CREATE TABLE
#4 · CREATE TABLE
#5 · CREATE TABLE
#6 · INSERT 0 25000
#7 · ANALYZE

tableoid says which partition each row physically lives in. ranges include the lower bound and exclude the upper, so midnight on april 1 belongs to april:

sqldb=events · session r
continues session r (1 earlier block run first)
SELECT tableoid::regclass AS partition, count(*) AS rows, min(occurred_at)::date AS first, max(occurred_at)::date AS last
FROM ev
GROUP BY tableoid
ORDER BY partition;
output, from postgres 18.6
SELECT 3
partitionregclassrowsint8firstdatelastdate
ev_2026_0385172026-03-012026-03-31
ev_2026_0479662026-04-012026-04-30
ev_2026_0585172026-05-012026-05-31
(3 rows)

pruning, at three moments

while planning. when the WHERE compares the key to constants, the planner checks each partition's bounds and leaves out the ones that can't match. they're not in the plan at all:

sqldb=events · session r
continues session r (2 earlier blocks run first)
EXPLAIN (COSTS OFF)
SELECT count(*) FROM ev
WHERE occurred_at >= '2026-04-01' AND occurred_at < '2026-04-15';
output, from postgres 18.6
EXPLAIN
Aggregate -> Seq Scan on ev_2026_04 ev Filter: ((occurred_at >= '2026-04-01 00:00:00+00'::timestamp with time zone) AND (occurred_at < '2026-04-15 00:00:00+00'::timestamp with time zone))

when the executor starts. a prepared statement with a generic plan doesn't know $1 while planning, so the plan keeps every partition. once the value arrives, the executor drops the ones that can't match before running anything, and EXPLAIN says how many with Subplans Removed:

sqldb=events · session r
continues session r (3 earlier blocks run first)
PREPARE by_day(timestamptz) AS
  SELECT count(*) FROM ev WHERE occurred_at >= $1 AND occurred_at < $1 + interval '1 day';
SET plan_cache_mode = force_generic_plan;
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF, TIMING OFF, SUMMARY OFF) EXECUTE by_day('2026-04-20');
output, from postgres 18.6
#1 · PREPARE
#2 · SET
#3 · EXPLAIN
Aggregate (actual rows=1.00 loops=1) -> Append (actual rows=275.00 loops=1) Subplans Removed: 2 -> Seq Scan on ev_2026_04 ev_1 (actual rows=275.00 loops=1) Filter: ((occurred_at >= $1) AND (occurred_at < ($1 + '1 day'::interval))) Rows Removed by Filter: 7691

while running. when the value only exists once part of the query has run (a subquery, or the outer side of a nested loop), every partition is set up, and the ones that turn out not to match are skipped. EXPLAIN marks them (never executed):

sqldb=events · session r
continues session r (4 earlier blocks run first)
RESET plan_cache_mode;
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM ev
WHERE occurred_at >= (SELECT max(occurred_at) FROM events) - interval '1 day';
output, from postgres 18.6
#1 · RESET
#2 · EXPLAIN
Aggregate (actual rows=1.00 loops=1) InitPlan 1 -> Aggregate (actual rows=1.00 loops=1) -> Seq Scan on events (actual rows=25000.00 loops=1) -> Append (actual rows=276.00 loops=1) -> Seq Scan on ev_2026_03 ev_1 (never executed) Filter: (occurred_at >= ((InitPlan 1).col1 - '1 day'::interval)) -> Seq Scan on ev_2026_04 ev_2 (never executed) Filter: (occurred_at >= ((InitPlan 1).col1 - '1 day'::interval)) -> Seq Scan on ev_2026_05 ev_3 (actual rows=276.00 loops=1) Filter: (occurred_at >= ((InitPlan 1).col1 - '1 day'::interval)) Rows Removed by Filter: 8241

all three need one thing: a condition on the partition key that postgres can compare with the bounds. without one, there's nothing to prune with.

predict the output
sql
EXPLAIN (COSTS OFF)
SELECT count(*) FROM ev WHERE user_id = 17;
sqldb=events · session r
continues session r (5 earlier blocks run first)
EXPLAIN (COSTS OFF)
SELECT count(*) FROM ev WHERE user_id = 17;
output, from postgres 18.6
EXPLAIN
Aggregate -> Append -> Seq Scan on ev_2026_03 ev_1 Filter: (user_id = 17) -> Seq Scan on ev_2026_04 ev_2 Filter: (user_id = 17) -> Seq Scan on ev_2026_05 ev_3 Filter: (user_id = 17)

list and hash

list partitions name their values. useful when the values are few and known, and queries ask for one of them:

sqldb=events · session l
CREATE TABLE ev_k (LIKE events INCLUDING DEFAULTS) PARTITION BY LIST (kind);
CREATE TABLE ev_k_browse PARTITION OF ev_k FOR VALUES IN ('view', 'click');
CREATE TABLE ev_k_buy    PARTITION OF ev_k FOR VALUES IN ('add_to_cart', 'purchase');
CREATE TABLE ev_k_signup PARTITION OF ev_k FOR VALUES IN ('signup');
INSERT INTO ev_k SELECT * FROM events ORDER BY id;
ANALYZE ev_k;
SELECT tableoid::regclass AS partition, kind, count(*) FROM ev_k GROUP BY tableoid, kind ORDER BY partition, kind;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · CREATE TABLE
#3 · CREATE TABLE
#4 · CREATE TABLE
#5 · INSERT 0 25000
#6 · ANALYZE
#7 · SELECT 5
partitionregclasskindtextcountint8
ev_k_browseclick4884
ev_k_browseview15112
ev_k_buyadd_to_cart2739
ev_k_buypurchase1765
ev_k_signupsignup500
(5 rows)

hash partitions take a hash of the key modulo n. no natural ranges, just a spread, and pruning only for equality on the key:

sqldb=events · session h
CREATE TABLE ev_h (LIKE events) PARTITION BY HASH (user_id);
CREATE TABLE ev_h0 PARTITION OF ev_h FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE ev_h1 PARTITION OF ev_h FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE ev_h2 PARTITION OF ev_h FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE ev_h3 PARTITION OF ev_h FOR VALUES WITH (MODULUS 4, REMAINDER 3);
INSERT INTO ev_h SELECT * FROM events ORDER BY id;
CREATE TABLE users_h (user_id int PRIMARY KEY, events int NOT NULL) PARTITION BY HASH (user_id);
CREATE TABLE users_h0 PARTITION OF users_h FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE users_h1 PARTITION OF users_h FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE users_h2 PARTITION OF users_h FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE users_h3 PARTITION OF users_h FOR VALUES WITH (MODULUS 4, REMAINDER 3);
INSERT INTO users_h SELECT user_id, count(*) FROM events GROUP BY user_id ORDER BY user_id;
ANALYZE ev_h, users_h;
SELECT tableoid::regclass AS partition, count(*) AS rows, count(DISTINCT user_id) AS users FROM ev_h GROUP BY tableoid ORDER BY partition;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · CREATE TABLE
#3 · CREATE TABLE
#4 · CREATE TABLE
#5 · CREATE TABLE
#6 · INSERT 0 25000
#7 · CREATE TABLE
#8 · CREATE TABLE
#9 · CREATE TABLE
#10 · CREATE TABLE
#11 · CREATE TABLE
#12 · INSERT 0 500
#13 · ANALYZE
#14 · SELECT 4
partitionregclassrowsint8usersint8
ev_h07248139
ev_h16245120
ev_h26283129
ev_h35224112
(4 rows)
range: ev_2026_038,517
range: ev_2026_047,966
range: ev_2026_058,517
list: ev_k_browse19,996
list: ev_k_buy4,504
list: ev_k_signup500
hash: ev_h07,248
hash: ev_h16,245
hash: ev_h26,283
hash: ev_h35,224
real output, postgres 18.6 (PGlite 0.5.12) · pruning
rows per partition, from the blocks above. months are close to even; list partitions are as uneven as the values (views dominate); hash spreads 500 users fairly evenly, but not their events, because a few users are much busier than the rest.

partitionwise join and aggregate

when every partition holds whole groups, postgres can aggregate each partition on its own and just append the answers. it's off by default (it makes planning more expensive), so turn it on where it pays:

sqldb=events · session l
continues session l (1 earlier block run first)
SET enable_partitionwise_aggregate = on;
EXPLAIN (COSTS OFF)
SELECT kind, count(*) FROM ev_k GROUP BY kind;
output, from postgres 18.6
#1 · SET
#2 · EXPLAIN
Append -> HashAggregate Group Key: ev_k.kind -> Seq Scan on ev_k_buy ev_k -> HashAggregate Group Key: ev_k_1.kind -> Seq Scan on ev_k_browse ev_k_1 -> HashAggregate Group Key: ev_k_2.kind -> Seq Scan on ev_k_signup ev_k_2

the same for joins: two tables partitioned the same way on the join key can be joined partition by partition, four small hash joins instead of one big one:

sqldb=events · session h
continues session h (1 earlier block run first)
SET enable_partitionwise_join = on;
EXPLAIN (COSTS OFF)
SELECT u.user_id, u.events, max(e.occurred_at)
FROM users_h AS u JOIN ev_h AS e USING (user_id)
GROUP BY u.user_id, u.events;
output, from postgres 18.6
#1 · SET
#2 · EXPLAIN
HashAggregate Group Key: u.user_id -> Append -> Hash Join Hash Cond: (e_1.user_id = u_1.user_id) -> Seq Scan on ev_h0 e_1 -> Hash -> Seq Scan on users_h0 u_1 -> Hash Join Hash Cond: (e_2.user_id = u_2.user_id) -> Seq Scan on ev_h1 e_2 -> Hash -> Seq Scan on users_h1 u_2 -> Hash Join Hash Cond: (e_3.user_id = u_3.user_id) -> Seq Scan on ev_h2 e_3 -> Hash -> Seq Scan on users_h2 u_3 -> Hash Join Hash Cond: (e_4.user_id = u_4.user_id) -> Seq Scan on ev_h3 e_4 -> Hash -> Seq Scan on users_h3 u_4

the rules that bite

a row whose key fits no partition is refused:

sqldb=events · session r
continues session r (6 earlier blocks run first)
INSERT INTO ev VALUES (25001, 42, 'view', '2026-06-01 09:00+00', NULL);
output, from postgres 18.6
ERROR 23514: no partition of relation "ev" found for row
DETAIL: Partition key of the failing row contains (occurred_at) = (2026-06-01 09:00:00+00).

a default partition catches everything that fits nowhere else. handy, until you create the partition those rows should have gone to, and postgres finds rows in the default that now belong elsewhere:

sqldb=events · session r
continues session r (7 earlier blocks run first)
CREATE TABLE ev_default PARTITION OF ev DEFAULT;
INSERT INTO ev VALUES (25001, 42, 'view', '2026-06-01 09:00+00', NULL);
SELECT tableoid::regclass AS partition, id FROM ev WHERE id = 25001;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 1
#3 · SELECT 1
partitionregclassidint8
ev_default25001
(1 row)
sqldb=events · session r
continues session r (8 earlier blocks run first)
CREATE TABLE ev_2026_06 PARTITION OF ev FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');
output, from postgres 18.6
ERROR 23514: updated partition constraint for default partition "ev_default" would be violated by some row

an index created on the parent is created on every partition, and on partitions added later. but a unique index is only enforced inside each partition, so it has to include the partition key, or two partitions could each hold the same id:

sqldb=events · session r
continues session r (9 earlier blocks run first)
ALTER TABLE ev ADD PRIMARY KEY (id);
output, from postgres 18.6
ERROR 0A000: unique constraint on partitioned table must include all partitioning columns
DETAIL: PRIMARY KEY constraint on table "ev" lacks column "occurred_at" which is part of the partition key.
sqldb=events · session r
continues session r (10 earlier blocks run first)
ALTER TABLE ev ADD PRIMARY KEY (id, occurred_at);
CREATE INDEX ev_user_idx ON ev (user_id);
SELECT tablename, indexname FROM pg_indexes WHERE tablename LIKE 'ev%' ORDER BY tablename, indexname;
output, from postgres 18.6
#1 · ALTER TABLE
#2 · CREATE INDEX
#3 · SELECT 11
tablenamenameindexnamename
evev_pkey
evev_user_idx
ev_2026_03ev_2026_03_pkey
ev_2026_03ev_2026_03_user_id_idx
ev_2026_04ev_2026_04_pkey
ev_2026_04ev_2026_04_user_id_idx
ev_2026_05ev_2026_05_pkey
ev_2026_05ev_2026_05_user_id_idx
ev_defaultev_default_pkey
ev_defaultev_default_user_id_idx
eventsevents_pkey
(11 rows)

and the payoff: old data leaves by detaching its partition. DETACH PARTITION ... CONCURRENTLY pg 14+ takes only a weak lock on the parent, so queries keep running while it happens. it refuses when there's a default partition, and it can't run inside a transaction block:

sqldb=events · session r
continues session r (11 earlier blocks run first)
ALTER TABLE ev DETACH PARTITION ev_2026_03 CONCURRENTLY;
output, from postgres 18.6
ERROR 55000: cannot detach partitions concurrently when a default partition exists
sqldb=events · session r
continues session r (12 earlier blocks run first)
DELETE FROM ev_default;
DROP TABLE ev_default;
ALTER TABLE ev DETACH PARTITION ev_2026_03 CONCURRENTLY;
SELECT count(*) AS still_in_ev FROM ev WHERE occurred_at < '2026-04-01';
SELECT count(*) AS now_standalone FROM ev_2026_03;
output, from postgres 18.6
#1 · DELETE 1
#2 · DROP TABLE
#3 · ALTER TABLE
#4 · SELECT 1
still_in_evint8
0
(1 row)
#5 · SELECT 1
now_standaloneint8
8517
(1 row)

march is now an ordinary table: archive it, dump it, or drop it in an instant, with no DELETE, no dead tuples and no VACUUM afterwards.

hover a stage.

the life of a monthly partition. hover a stage.

when it doesn't help

partitioning makes a query faster only when it filters on the key and the skipped partitions were worth skipping. with an index on occurred_at, a one-table query for one day already reads only that day's pages. what partitioning really buys is operational: dropping old data instantly, vacuuming and reindexing one month at a time, indexes that stay small. it costs planning time (each partition is one more relation to consider), and queries without the key now visit every partition. a few large partitions beat thousands of tiny ones. and every partition still lives on one server: spreading them across machines is sharding.

keylines

  • one table name, many real tables, split by a key: range, list or hash.
  • pruning skips partitions at plan time, at executor start (Subplans Removed) or at run time (never executed).
  • no condition on the key, no pruning: every partition is read.
  • unique indexes must include the partition key.
  • retention becomes DETACH CONCURRENTLY and DROP, not DELETE and VACUUM.