Mental model
Declarative Table Partitioning splits a single logical table into smaller physical child tables on disk (CREATE TABLE ... PARTITION OF ...) while exposing a unified SQL interface to application code. Instead of maintaining one multi-terabyte B-Tree index whose hot upper levels thrash shared buffers and whose dead tuples overwhelm autovacuum during bulk deletes, partitioning bounds every sub-index to a localized working set and replaces expensive DELETE sweeps with instant metadata drops (DROP TABLE or ALTER TABLE ... DETACH PARTITION CONCURRENTLY). When query filters include the partition key, PostgreSQL's planner and executor prune irrelevant children before touching heap pages.
Theory
PostgreSQL provides three built-in declarative partitioning dimensions—plus multi-level sub-partitioning—allowing teams to match physical storage geometry to workload access and retention profiles:
| Partitioning Strategy | Syntax & Routing Rule | Ideal Workload | Pruning Behavior | Operational Advantage |
|---|---|---|---|---|
| Range | PARTITION BY RANGE (recorded_at) with contiguous [FROM, TO) bounds | Time-series telemetry, audit logs, financial ledgers, event streams | Eliminates out-of-range time slices on inequality or equality bounds | Instant zero-bloat data expiration via DETACH PARTITION CONCURRENTLY + DROP TABLE |
| List | PARTITION BY LIST (region) mapping discrete key sets ('us-east', 'eu-central') | Multi-region residency (GDPR), lifecycle state flags, tier separation | Matches exact IN (...) or = predicates directly to target partition | Keeps isolated regulatory regions cleanly mountable on separate tablespaces |
| Hash | PARTITION BY HASH (tenant_id) assigning modulo remainder across buckets | Uniformly balancing hot multi-tenant key spaces when no natural date retention applies | Prunes only on strict equality (tenant_id = $1), never inequalities | Prevents write hot-spotting and caps single B-Tree depth across buckets |
Planning-Time Pruning, Execution-Time Pruning, and Partition-Wise Joins
PostgreSQL performs partition pruning at two distinct lifecycle points depending on whether filter literals are statically visible:
- Plan-Time Pruning: Occurs before execution when predicates carry constants (
WHERE recorded_at >= '2026-10-01'), avoiding lock acquisition and execution node allocation entirely for excluded partitions. - Execution-Time Pruning: Triggers inside
Append/MergeAppendexecution nodes when filter values come from prepared statement parameters ($1), subqueries, or nested-loop join outer columns (InitPlan/ runtime parameter binding). Even withenable_partition_pruning = on, keep active partition counts per table realistic—usually dozens to a few hundred rather than10,000+tiny child tables—because planning latency and catalog lock fan-out scale linearly with non-pruned partitions during metadata lookups.
Furthermore, PostgreSQL imposes a structural rule on uniqueness: every PRIMARY KEY or UNIQUE constraint on a partitioned table must include all partition key columns. This guarantees uniqueness locally inside each child partition without cross-partition B-Tree locking during inserts.
sql-- Declarative range-partitioned telemetry table with composite primary keyCREATE TABLE metrics (metric_id UUID NOT NULL,recorded_at TIMESTAMPTZ NOT NULL,tenant_id BIGINT NOT NULL,payload JSONB NOT NULL,PRIMARY KEY (recorded_at, metric_id)) PARTITION BY RANGE (recorded_at);-- Indexes created on the parent automatically propagate to existing & future partitionsCREATE INDEX idx_metrics_tenant_time ON metrics (tenant_id, recorded_at DESC);-- Pre-create monthly partitions before writes arrive (e.g., via pg_partman)CREATE TABLE metrics_2026_11 PARTITION OF metricsFOR VALUES FROM ('2026-11-01 00:00:00Z') TO ('2026-12-01 00:00:00Z');CREATE TABLE metrics_2026_12 PARTITION OF metricsFOR VALUES FROM ('2026-12-01 00:00:00Z') TO ('2027-01-01 00:00:00Z');-- Always add a DEFAULT catch-all only cautiously; unpartitioned backlog can block clean range splits-- Retention without table-wide bloat or long ACCESS EXCLUSIVE locks:ALTER TABLE metrics DETACH PARTITION metrics_2025_11 CONCURRENTLY;DROP TABLE metrics_2025_11;
Enabling enable_partitionwise_join = on and enable_partitionwise_aggregate = on allows PostgreSQL to execute matching joins and GROUP BY aggregations locally within matching partition pairs (metrics_2026_11 JOIN events_2026_11), reducing memory pressure for hash tables dramatically—at the cost of slightly higher query planning time.
Alternatives and trade-offs
- PostgreSQL Declarative Partitioning (Single Node): Eliminates vacuum bloat, accelerates cold archiving via
DETACH PARTITION CONCURRENTLY, and keeps active indexes RAM-resident with zero distributed network joins; however, write throughput remains capped by one PostgreSQL primary node's CPU and storage bandwidth. - Partial Indexes on Unpartitioned Tables: Effective when
95%of reads hit recent rows and the table does not need bulk TTL drops (WHERE status = 'active'), avoiding query planning complexity on partition trees altogether. - Horizontal Sharding (Citus / Vitess / Application Sharding): Required once single-node primary write IOPS, WAL replication throughput, or NVMe capacity is exhausted—at the high engineering cost of cross-shard distributed transactions and resharding topology changes.
Failure modes and misconceptions
- Missing Partition Key in Queries (Partition Explosion): Issuing
SELECT * FROM metrics WHERE metric_id = $1withoutrecorded_atforces PostgreSQL to scan indexes across every historical child partition (NB-Trees instead of1), degrading point-lookup latency linearly with table age. - Wrapping the Partition Key in Functions: Predicates like
WHERE date_trunc('month', recorded_at) = '2026-11-01'disable range pruning because PostgreSQL cannot invert arbitrary function calls into raw column bounds. Rewrite predicates as sargable ranges (recorded_at >= '2026-11-01' AND recorded_at < '2026-12-01'). - Partition Over-Granularity (
3,000+Hourly Partitions): Creating thousands of tiny daily or hourly partitions bloatspg_classlock acquisition (AccessShareLockon every scanned partition per query) and skyrockets planning latency and memory per backend. Match slice cadence (weekly, monthly) so active working sets stay between5 GBand50 GBper partition. - Blocking Production Traffic During Retention (
DETACH PARTITIONvsCONCURRENTLY): Running standardALTER TABLE ... DETACH PARTITIONgrabsACCESS EXCLUSIVEon the parent table, queueing all reads and writes behind long queries. Use PostgreSQL 14+DETACH PARTITION CONCURRENTLYto detach partitions safely without blocking concurrent OLTP transactions.
Decision scenario
Your AI observability pipeline ingests 120 million trace spans per day (~1.8 TB every 90 days) and runs rolling 90-day retention drops while serving live tenant queries filtered by (tenant_id, created_at). Partition trace_spans declaratively using Range partitioning by week on created_at (PRIMARY KEY (created_at, span_id)), create composite parent indexes (tenant_id, created_at DESC), enforce (created_at >= ...) in every service query predicate for compile/runtime pruning, automate future partition creation ahead of clock rollover via pg_partman, and reclaim expired storage weekly using non-blocking ALTER TABLE ... DETACH PARTITION ... CONCURRENTLY followed by archival or DROP TABLE.
Learning outcomes
- Select between Range, List, and Hash partitioning strategies based on time-series retention, data residency, and tenant skew.
- Explain how plan-time and runtime partition pruning behave with parameterized queries and non-sargable predicates.
- Enforce PostgreSQL's partition-key uniqueness constraints and choose optimal partition sizes to avoid planning lock bloat.
- Automate zero-downtime data retention with
DETACH PARTITION CONCURRENTLY.
Trade-offs
Declarative partitioning transforms multi-terabyte vacuum bottlenecks and index-cache misses into bounded partition maintenance and instant metadata drops, but demands strict discipline on sargable partition predicates, composite unique keys, and reasonable partition counts (< 500 active children per table).