Working with SQL Partitioning

1. Understanding Partitioning Benefits

BenefitHow
Partition pruningPlanner skips irrelevant partitions
Faster maintenanceDETACH partition for fast bulk archive
Index sizeSmaller per-partition indexes fit in memory
Parallel opsVacuum/analyze per partition
LifecycleDROP old partitions in O(1)

2. Creating Range Partitions

Example: Postgres Range Partitioning

CREATE TABLE events (
  id SERIAL, ts TIMESTAMPTZ NOT NULL, payload JSONB
) PARTITION BY RANGE (ts);

CREATE TABLE events_2026_05 PARTITION OF events
  FOR VALUES FROM ('2026-05-01') TO ('2026-06-01');
CREATE TABLE events_2026_06 PARTITION OF events
  FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');
UseExample
Time-basedOne partition per month/day
Numeric rangeid ranges for sharding
Default partitionCatches rows outside defined ranges

3. Creating List Partitions

PropertyDetail
Discrete valuese.g., region IN ('US','EU','APAC')
Syntax (PG)FOR VALUES IN ('US','CA')
UseGeographic, status, tenant grouping

4. Creating Hash Partitions

PropertyDetail
Even distributionHash of key % modulus
Syntax (PG)FOR VALUES WITH (MODULUS 8, REMAINDER 0..7)
UseWrite hotspot avoidance, balanced shards
LimitationNo range pruning, must include hash key in queries

5. Creating Composite Partitions

StrategyExample
Range + HashRange by month, sub-hash by user_id
List + RangeList by region, sub-range by date
Sub-partitionMulti-level partition tree

6. Querying Partitioned Tables

TipDetail
Include partition key in WHEREEnables pruning
EXPLAINVerify only relevant partitions scanned
Constraint exclusion (PG)SET constraint_exclusion = partition; (legacy)
Cross-partition queriesSlow — scan all partitions

7. Managing Partitions

OperationSyntax (PG)
AttachALTER TABLE parent ATTACH PARTITION child FOR VALUES ...;
DetachALTER TABLE parent DETACH PARTITION child;
DropDROP TABLE child;
Toolspg_partman (automation)

8. Indexing Partitioned Tables

AspectDetail
Partitioned index (PG 11+)Create on parent; auto-propagates
Local indexPer-partition, can use different strategies
Global index (Oracle)One index across all partitions
Unique across partitionsMust include partition key in PG

9. Maintaining Partition Statistics

TaskDetail
ANALYZE per partitionImportant for accurate planning
Autovacuum tuningPer-partition thresholds for hot partitions
Incremental stats (Oracle)Only re-stat changed partitions

10. Migrating Data Between Partitions

OperationApproach
Move row across partitionsUPDATE key column triggers move (PG 11+)
ReorgDetach, rewrite, re-attach
ArchiveDetach + move to cold storage
Split / merge partitionsCustom SQL or pg_partman