Partitioning Postgres Tables: Types, Indexing, and Automating with pg_partman
Once a table gets large enough that queries only ever touch a slice of it — the last
90 days, one tenant, one region — partitioning lets Postgres skip the rest of the
table entirely (partition pruning) instead of scanning it. The tradeoff is that
partitioning isn’t “set once and forget it” — new partitions have to exist before
data needs them, and old ones eventually need to be dropped. That’s the gap
pg_partman fills.
Partition Types
Postgres has three native declarative partitioning strategies. The right one depends entirely on how the data is queried, not just what the column looks like.
Range Partitioning
Splits rows by a range of values on the partition key — the most common choice for time-series or append-heavy tables.
CREATE TABLE trades (
id BIGINT GENERATED ALWAYS AS IDENTITY,
symbol TEXT NOT NULL,
traded_at TIMESTAMPTZ NOT NULL,
price NUMERIC
) PARTITION BY RANGE (traded_at);
CREATE TABLE trades_2026_08 PARTITION OF trades
FOR VALUES FROM ('2026-08-01') TO ('2026-09-01');
A date/timestamp column is the classic range key (monthly or daily partitions),
but a numeric/serial ID range works the same way — e.g. partitioning an orders
table by order_id in blocks of 1,000,000, which is useful when there’s no natural
date column but IDs are still monotonically increasing.
List Partitioning
Splits rows by an explicit set of discrete values — a good fit for a fixed or
slow-changing set of categories, like region or tenant_id.
CREATE TABLE orders (
id BIGINT,
region TEXT NOT NULL,
amount NUMERIC
) PARTITION BY LIST (region);
CREATE TABLE orders_apac PARTITION OF orders FOR VALUES IN ('IN', 'SG', 'AU');
CREATE TABLE orders_emea PARTITION OF orders FOR VALUES IN ('UK', 'DE', 'FR');
Hash Partitioning
Splits rows by hashing the partition key into a fixed number of buckets — used when
there’s no natural range or list grouping and the goal is just to spread rows (and
write load) evenly, e.g. hashing a user_id or any other string/UUID value where
the values themselves carry no useful ordering.
CREATE TABLE sessions (
id UUID,
user_id UUID NOT NULL,
created_at TIMESTAMPTZ
) PARTITION BY HASH (user_id);
CREATE TABLE sessions_0 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE sessions_1 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 1);
-- ...and so on for REMAINDER 2, 3
Hash partitioning trades pruning for distribution — a query filtering on user_id
still only hits one partition, but a range scan across all users has to hit every
partition, since there’s no ordering to exploit.
Partition Pruning: Why the Query Has to Know the Range
Partitioning only pays off if the query tells Postgres which slice it needs. You
still query the parent table — never the individual partition tables directly in
normal application code — but the WHERE clause has to constrain the partition key
itself, or the planner has no basis to exclude anything:
-- Prunes to a single partition — the planner can see this only touches trades_2026_08
EXPLAIN SELECT * FROM trades
WHERE traded_at >= '2026-08-01' AND traded_at < '2026-09-01';
-- Scans every partition — nothing here constrains traded_at
EXPLAIN SELECT * FROM trades WHERE symbol = 'AAPL';
In the first query’s plan, you’d see a single Seq Scan on trades_2026_08 (or an
index scan, if one exists) under the Append node. In the second, every partition
shows up under the Append — Postgres has no choice but to check each one, since
symbol isn’t the partition key and nothing rules any partition out.
Two practical implications:
- Design the partition key around your actual query patterns, not just around
what seems like a natural column to split on. If most queries filter by
traded_at, range-partitioning on it is a real win. If most queries filter bysymbolinstead, partitioning bytraded_atbuys index/vacuum benefits but not query-time pruning for those lookups — you’d still want an index onsymbolwithin each partition. - Pruning also works with bind parameters at execution time (“runtime
pruning,” on by default via
enable_partition_pruning), so a prepared statement or a value from a subquery still prunes correctly — it isn’t limited to literal constants written directly in the SQL.
EXPLAIN (not just EXPLAIN ANALYZE) is the way to confirm pruning is actually
happening — if a query that should hit one partition shows every partition under
Append, the WHERE clause isn’t constraining the partition key the way it looks
like it should.
Partitioning and Indexes
An index created on the parent (partitioned) table is a partitioned index: it automatically creates a matching local index on every existing partition, and on every partition attached later.
CREATE INDEX idx_trades_symbol ON trades (symbol);
That one statement creates real, independent B-tree indexes on trades_2026_08 and
every other current or future partition — there’s nothing extra to do per partition.
What it does not do is create one global index spanning all partitions physically;
each partition’s index only indexes that partition’s own rows, and Postgres uses
partition pruning first, then the relevant local index.
Two things this changes about constraints:
- Unique/primary key constraints must include the partition key. Postgres can’t
enforce global uniqueness across separate partitions without it, so
PRIMARY KEY (id)alone is rejected on a partitioned table unlessidis (or includes) the partition key — in practice this usually means widening the key toPRIMARY KEY (id, traded_at)or similar. - An index created directly on a single partition (rather than on the parent)
stays local to that partition only — it won’t appear on the parent or on siblings,
which is occasionally useful (e.g. a specialized index on one hot partition) but
easy to do by accident if you’re not paying attention to which table you ran
CREATE INDEXagainst.
Automating with pg_partman
Native partitioning gives you the structure; it doesn’t create tomorrow’s partition
for you or drop the one from three years ago. pg_partman handles both.
Setup for a range-partitioned table:
CREATE EXTENSION pg_partman;
SELECT partman.create_parent(
p_parent_table := 'public.trades',
p_control := 'traded_at',
p_interval := 'monthly'
);
UPDATE partman.part_config
SET premake = 4,
retention = '12 months',
retention_keep_table = false
WHERE parent_table = 'public.trades';
premake— how many future partitions to keep pre-created at all times (here, 4 months ahead)retention— how old a partition can get before it’s dropped (or detached, ifretention_keep_tableis true and you’d rather archive than delete)
partman.run_maintenance() is the function that actually creates the next
partition(s) and enforces retention — it’s meant to run on a schedule (pg_cron is
the usual choice) rather than manually.
Partitioning an Existing Table
Everything above assumes the table is partitioned from the start. There’s no
ALTER TABLE ... PARTITION BY in Postgres — you can’t convert an existing plain
table into a partitioned one in place. Partitioning has to be baked in at
CREATE TABLE time, so migrating an existing table means building a new
partitioned table alongside it and moving the data across.
-
Move the existing table out of the way.
ALTER TABLE trades RENAME TO trades_old;This is metadata-only — no data is rewritten — but it does take a brief
ACCESS EXCLUSIVElock, so run it back-to-back with the next step rather than leaving a gap where nothing namedtradesexists. -
Create the new partitioned table under the original name.
CREATE TABLE trades (LIKE trades_old INCLUDING ALL) PARTITION BY RANGE (traded_at);INCLUDING ALLcopies columns, defaults, and constraints from the old table. Check the result with\d tradesafterward — depending on version, it’s often safer to add indexes explicitly on the new parent rather than rely onLIKEto carry them over, since it’s the explicitCREATE INDEXon the parent that guarantees cascading to every partition (covered above). -
Set up the partitioning config, same as for a fresh table — including the extension itself, if this is the first table on the instance to use it.
CREATE EXTENSION IF NOT EXISTS pg_partman; SELECT partman.create_parent('public.trades', 'traded_at', 'monthly'); -
Migrate the historical data in batches, not one long
INSERT ... SELECT. pg_partman ships a helper for exactly this — by default it looks for a source table named<parent>_old, matching the rename in step 1:SELECT partman.partition_data_time( 'public.trades', p_batch_count := 10, p_batch_interval := '1 month' );It copies rows into the correct partitions a batch at a time and removes them from
trades_oldas it goes — bounding both the transaction size and the WAL spike, instead of holding one giant transaction open for the whole table. -
Verify, then drop the old table once
trades_oldis empty and the application has been reading/writing against the new partitionedtradeswithout issue.DROP TABLE trades_old;
The Impact of Creating Future Partitions — and How to Avoid It
Attaching a new partition takes a brief lock on the parent table, and in older Postgres versions (pre-11), attaching a partition with existing data required a full table scan to validate the partition’s constraints — expensive if it happens while the table is under load.
pg_partman sidesteps most of this by design:
- New partitions are created empty, directly as partitions (
CREATE TABLE ... PARTITION OF ...), not built separately and attached later — so there’s no validation scan to worry about, since an empty partition trivially satisfies its own constraint. - Because
premakekeeps partitions created well ahead of when data actually needs to land in them, the (brief) locking from partition creation happens during a scheduled maintenance run — not at the exact moment the application starts writing rows that need a partition that doesn’t exist yet.
What’s still worth planning for:
- Run
run_maintenance()on a schedule, off peak, even though the lock is brief — on a busy table, “brief” and “zero” aren’t the same thing.premakeneeds headroom — if it’s too low (or maintenance doesn’t run for a while), the pipeline can catch up to the last pre-made partition, forcing a same-moment creation right when it’s needed.
- Dropping old partitions is the riskier direction, not creating new ones — on
Postgres 14+, use
DETACH PARTITION ... CONCURRENTLY(whichpg_partmansupports via configuration) so old partitions can be detached without blocking reads/writes on the rest of the table.
Concepts demonstrated
- Declarative partitioning: range, list, and hash strategies, and which query pattern each one actually fits
- Partition pruning: why the payoff depends on the query constraining the
partition key, and how to confirm it with
EXPLAIN - Partitioned indexes: how an index on the parent cascades to every partition, current and future, and why unique constraints need the partition key
- pg_partman:
create_parent,part_config(premake,retention), andrun_maintenanceas the automation layer over native partitioning - Migrating existing tables: why partitioning can’t be applied in place, and how to cut over via rename + recreate + batched data migration instead
- Operational safety: why pre-creating partitions avoids reactive, under-load partition creation, and why detaching old partitions concurrently matters more than creating new ones