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:
- 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.
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.
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;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:
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;| partitionregclass | rowsint8 | firstdate | lastdate |
|---|---|---|---|
| ev_2026_03 | 8517 | 2026-03-01 | 2026-03-31 |
| ev_2026_04 | 7966 | 2026-04-01 | 2026-04-30 |
| ev_2026_05 | 8517 | 2026-05-01 | 2026-05-31 |
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:
EXPLAIN (COSTS OFF)
SELECT count(*) FROM ev
WHERE occurred_at >= '2026-04-01' AND occurred_at < '2026-04-15';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:
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');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):
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';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.
EXPLAIN (COSTS OFF)
SELECT count(*) FROM ev WHERE user_id = 17;EXPLAIN (COSTS OFF)
SELECT count(*) FROM ev WHERE 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:
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;| partitionregclass | kindtext | countint8 |
|---|---|---|
| ev_k_browse | click | 4884 |
| ev_k_browse | view | 15112 |
| ev_k_buy | add_to_cart | 2739 |
| ev_k_buy | purchase | 1765 |
| ev_k_signup | signup | 500 |
hash partitions take a hash of the key modulo n. no natural ranges, just a spread, and pruning only for equality on the key:
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;| partitionregclass | rowsint8 | usersint8 |
|---|---|---|
| ev_h0 | 7248 | 139 |
| ev_h1 | 6245 | 120 |
| ev_h2 | 6283 | 129 |
| ev_h3 | 5224 | 112 |
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:
SET enable_partitionwise_aggregate = on;
EXPLAIN (COSTS OFF)
SELECT kind, count(*) FROM ev_k GROUP BY kind;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:
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;the rules that bite
a row whose key fits no partition is refused:
INSERT INTO ev VALUES (25001, 42, 'view', '2026-06-01 09:00+00', NULL);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:
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;| partitionregclass | idint8 |
|---|---|
| ev_default | 25001 |
CREATE TABLE ev_2026_06 PARTITION OF ev FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');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:
ALTER TABLE ev ADD PRIMARY KEY (id);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;| tablenamename | indexnamename |
|---|---|
| ev | ev_pkey |
| ev | ev_user_idx |
| ev_2026_03 | ev_2026_03_pkey |
| ev_2026_03 | ev_2026_03_user_id_idx |
| ev_2026_04 | ev_2026_04_pkey |
| ev_2026_04 | ev_2026_04_user_id_idx |
| ev_2026_05 | ev_2026_05_pkey |
| ev_2026_05 | ev_2026_05_user_id_idx |
| ev_default | ev_default_pkey |
| ev_default | ev_default_user_id_idx |
| events | events_pkey |
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:
ALTER TABLE ev DETACH PARTITION ev_2026_03 CONCURRENTLY;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;| still_in_evint8 |
|---|
| 0 |
| now_standaloneint8 |
|---|
| 8517 |
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.
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.