PostgreSQL Table Partitioning: Range, Hash, and When Pruning Actually Fires

Every growing service eventually meets the same table. It starts as a simple events or orders table, ingest is fast, queries are indexed, everyone is happy. Two years later it holds hundreds of millions of rows, the nightly DELETE FROM events WHERE created_at < now() - interval '90 days' takes three hours, autovacuum chases bloat it can never reclaim, and even indexed lookups slow down because the indexes themselves are gigabytes deep. Partitioning is PostgreSQL’s structural answer to this lifecycle: split one logical table into many physical ones, and let the planner route each query to only the pieces that matter.

Declarative partitioning has been in PostgreSQL since version 10, with hash partitioning added in version 11, and it has quietly matured into a production-grade feature. The catch is that partitioning done casually can make things worse: the planner spends more time, unique constraints get weaker, and queries that forget the partition key scan every partition anyway. This post walks through the three partitioning strategies, the mechanics of partition pruning, and the operational traps that show up only after you have committed to the design.

The Three Strategies

RANGE partitioning assigns rows to partitions based on non-overlapping bounds of a column — the workhorse for time-series and event data:

CREATE TABLE events (
    id          bigint GENERATED ALWAYS AS IDENTITY,
    created_at  timestamptz NOT NULL,
    device_id   bigint NOT NULL,
    payload     jsonb,
    PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);

CREATE TABLE events_2026_11 PARTITION OF events
    FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE TABLE events_2026_12 PARTITION OF events
    FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');

Bounds are lower-inclusive and upper-exclusive, so consecutive monthly partitions tile the timeline with no gaps and no overlaps. LIST partitioning maps rows to partitions by explicit values — useful for regional sharding (FOR VALUES IN ('eu', 'us', 'apac')). HASH partitioning spreads rows across N partitions by hashing the key, which gives you an even split when no natural range exists:

CREATE TABLE sessions (
    session_id  uuid NOT NULL,
    user_id     bigint NOT NULL,
    data        jsonb,
    PRIMARY KEY (session_id, user_id)
) PARTITION BY HASH (user_id);

CREATE TABLE sessions_p0 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE sessions_p1 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE sessions_p2 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE sessions_p3 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 3);

Each strategy buys something different. RANGE gives you cheap retention (more on that below) and excellent pruning for time-bounded queries. HASH gives you balanced size without range semantics. LIST gives you explicit control over where data lives. None of them give you everything, and choosing the partition key is the single most consequential decision in the design.

Pruning: Where the Performance Actually Comes From

The payoff of partitioning is partition pruning: the planner inspects each partition’s bounds against the query’s WHERE clause and drops any partition that provably cannot contain matching rows. The work happens in two distinct places, and the difference matters in production.

With literal constants in the query, pruning happens at plan time. Run EXPLAIN and you can verify it directly:

EXPLAIN SELECT count(*) FROM events
WHERE created_at >= '2026-12-10' AND created_at < '2026-12-11';

-- Append
--   -> Seq Scan on events_2026_12
-- (events_2026_11 never appears: pruned)

With prepared statements or parameterized queries, the values may not be known at plan time, so PostgreSQL defers pruning to execution time, pruning per-parameter-value on each execution. This is why the same query can show a healthy pruned plan in one session and a full Append over every partition in another — if you are testing pruning, make sure your plan is not being cached with generic parameters before you conclude it is broken.

The rule that governs everything: pruning only fires when the partition key appears in the query. A query on device_id against a table range-partitioned on created_at touches every partition. This is why the PostgreSQL documentation recommends partitioning by the column that most commonly appears in WHERE clauses — usually the one your retention policy and your access pattern both agree on. For time-series data that alignment is natural; for entity-shaped tables it often is not, and hash on the entity id is the fallback.

The Traps

Unique constraints get narrower. A unique or primary key constraint on a partitioned table must include every partition key column. PostgreSQL enforces uniqueness within each partition separately, so it cannot guarantee uniqueness of a value unless the partition key is part of the constraint — otherwise two rows with the same id could land in different partitions legally. That is why both examples above declare PRIMARY KEY (id, created_at). Uniqueness on the id alone is now your application’s job (or the job of a lookup table with the real unique constraint). This is the trap that surprises teams mid-migration: you cannot simply keep the old PRIMARY KEY (id).

Partition count is not free. Every partition the planner must consider adds planning time and memory. Thousands of partitions with a query that cannot prune make planning itself the bottleneck. Right-size the granularity — monthly partitions for a decade of history is 120 partitions, which is fine; per-hour partitions for a decade is not. Sub-partitioning (range by month, hash within each month) is the tool when one hot partition would otherwise dwarf the rest.

Row movement on UPDATE. If an UPDATE changes the partition key to a value outside the row’s current partition, PostgreSQL silently moves the row — a delete plus insert across partitions. That breaks naive assumptions about triggers and can surprise logical replication consumers, since the change may surface as separate delete and insert events.

The default partition is a liquidity trap. A DEFAULT partition catches anything the other bounds miss, which looks like convenient insurance. But attaching a new partition requires checking that the default partition contains no rows falling into the new bounds — a full scan of the default under a lock. With a large default partition, creating next month’s partition becomes a slow, locking operation. Keep the default empty by construction, or expect pain.

Retention: The Reason Most Teams Partition

The operational win that justifies partitioning for high-volume tables is data expiry. Compare the two ways to drop old data:

-- Slow: scans, locks, leaves dead tuples for autovacuum
DELETE FROM events WHERE created_at < '2026-11-01';

-- Instant: the partition stops being part of the table, period
ALTER TABLE events DETACH PARTITION events_2026_11;
DROP TABLE events_2026_11;

Detach returns immediately regardless of partition size, and the storage is reclaimed when you drop the now-standalone table — no vacuum debt, no long locks, no replication lag spike. Detached partitions can also be archived to cold storage first, which deletes never allow. This single capability is why time-series workloads in PostgreSQL almost always end up range-partitioned by a time column.

Automating the lifecycle — creating future partitions ahead of time and detaching expired ones — is standard practice, and tools like pg_partman exist precisely because hand-managed partition schedules eventually fail at 2 a.m. on the first of the month. Whatever mechanism you use, the create-ahead job should run well before the boundary; queries against a range with no partition fail outright rather than degrading.

When Partitioning Is and Isn’t the Answer

Partitioning is not an indexing substitute. A 10 GB table with well-chosen indexes that answers every query in milliseconds gains nothing from being split. The documentation’s own guidance boils down to: partition when a table would remain problematic in spite of indexing — huge tables whose working set no longer fits usefully in memory, tables dominated by range queries against one column, and tables with aggressive retention requirements. In exchange you accept weaker unique constraints, more planning surface, and a partition-management job that is now part of your production critical path.

Done deliberately, though, it is one of the highest-leverage structural changes available in PostgreSQL: queries that touch a bounded slice of time get faster without a single index change, retention becomes a metadata operation, and the table’s growth stops being a slow-motion emergency. Start by verifying with EXPLAIN that your most important queries actually prune — that one check tells you within minutes whether the design will pay off.

Leave a Reply

Your email address will not be published. Required fields are marked *