Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Master declarative table partitioning in PostgreSQL. Learn RANGE, LIST, and HASH partitioning syntax, partition pruning, and maintenance strategies.
Quick answer
PostgreSQL table partitioning divides large tables into distinct physical child tables using declarative RANGE, LIST, or HASH strategies. It accelerates queries by pruning unneeded partitions during query planning and allows instant data archiving by dropping partition tables instead of running expensive DELETE commands.
FAQs
Can I change the partition key of an existing row in PostgreSQL?
Yes. If an UPDATE statement changes the partition key value, PostgreSQL automatically deletes the row from the old partition and inserts it into the new partition.
How many partitions can a single PostgreSQL table have?
While PostgreSQL supports thousands of partitions, having more than a few hundred can degrade planning time. Aim to keep partition counts under 500 per table.
Are indexes on the parent table inherited by child partitions?
Yes. Indexes created on the parent table are automatically created on all existing and future child partitions.
What happens if I insert a row that does not fit any partition range?
PostgreSQL will throw an error and abort the transaction unless you have created a DEFAULT partition for the table.
Build fast text search directly in PostgreSQL without external search engines. Master to_tsvector, to_tsquery, relevance ranking with ts_rank, and GIN indexes.
Declarative table partitioning in PostgreSQL allows a single logical table to be stored as multiple physical tables on disk. When tables grow to tens of gigabytes, sequential scans become unbearable and B-tree indexes spill out of memory. Partitioning restores performance by allowing the query planner to read only the partitions containing data relevant to your query.
PostgreSQL provides three distinct partitioning strategies: range, list, and hash. Selecting the correct method depends on your data access patterns and whether your primary query filters are dates, discrete categories, or arbitrary identifiers.
Understanding declarative partitioning
Prior to PostgreSQL 10, partitioning required complex table inheritance, custom triggers, and rule systems that were difficult to maintain. Modern declarative partitioning defines the partitioning strategy directly on the parent table with the PARTITION BY clause.
The parent table itself holds no storage; it serves as a routing schema. Child partitions are independent tables attached to the parent with boundary conditions. PostgreSQL automatically creates indexes on all child partitions when you create an index on the parent table. Read the official PostgreSQL CREATE TABLE documentation for exact DDL parameter rules.
Range partitioning: syntax and time-series patterns
Range partitioning assigns rows based on ranges of values, most commonly dates or sequential numbers. The range boundaries are non-overlapping and defined as FROM (start) TO (end), where the start value is inclusive and the end value is exclusive.
PostgreSQL range partitioning by month
-- Create logical partitioned parent tableCREATE TABLE audit_logs ( id BIGINT GENERATED ALWAYS AS IDENTITY, user_id INT NOT NULL, action VARCHAR(50) NOT NULL, created_at TIMESTAMPTZ NOT NULL, payload JSONB, PRIMARY KEY (id, created_at)) PARTITION BY RANGE (created_at);-- Create monthly child partitionsCREATE TABLE audit_logs_2026_10 PARTITION OF audit_logs FOR VALUES FROM ('2026-10-01 00:00:00+00') TO ('2026-11-01 00:00:00+00');CREATE TABLE audit_logs_2026_11 PARTITION OF audit_logs FOR VALUES FROM ('2026-11-01 00:00:00+00') TO ('2026-12-01 00:00:00+00');
In the example above, the primary key must include created_at. PostgreSQL mandates that any unique constraint or primary key on a partitioned table must include all columns in the partition key.
List partitioning: categorical routing
List partitioning routes rows based on explicit lists of literal values. It is ideal for data sets with distinct categories such as geographic regions, tenant tiers, or business divisions.
List partitioning by geographic region
CREATE TABLE client_accounts ( account_id INT NOT NULL, company_name VARCHAR(100) NOT NULL, region VARCHAR(10) NOT NULL, contract_status VARCHAR(20) NOT NULL, PRIMARY KEY (account_id, region)) PARTITION BY LIST (region);-- Define partitions for specific value listsCREATE TABLE client_accounts_na PARTITION OF client_accounts FOR VALUES IN ('US', 'CA', 'MX');CREATE TABLE client_accounts_emea PARTITION OF client_accounts FOR VALUES IN ('UK', 'DE', 'FR', 'ES', 'IT');-- Optional default partition catches any unmapped regionsCREATE TABLE client_accounts_default PARTITION OF client_accounts DEFAULT;
Always consider adding a DEFAULT partition for list-partitioned tables. If an application attempts to insert a row with an unmapped value and no default partition exists, PostgreSQL raises an error and rejects the transaction.
Hash partitioning: even distribution across buckets
When your dataset lacks natural ranges or categories but suffers from high insert contention on primary keys, hash partitioning distributes rows evenly across a fixed number of modulus buckets.
Hash partitioning syntax
CREATE TABLE device_telemetry ( device_uuid UUID NOT NULL, metric_name VARCHAR(50) NOT NULL, metric_value DOUBLE PRECISION NOT NULL, recorded_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (device_uuid, recorded_at)) PARTITION BY HASH (device_uuid);-- Create 4 hash bucketsCREATE TABLE device_telemetry_b0 PARTITION OF device_telemetry FOR VALUES WITH (MODULUS 4, REMAINDER 0);CREATE TABLE device_telemetry_b1 PARTITION OF device_telemetry FOR VALUES WITH (MODULUS 4, REMAINDER 1);CREATE TABLE device_telemetry_b2 PARTITION OF device_telemetry FOR VALUES WITH (MODULUS 4, REMAINDER 2);CREATE TABLE device_telemetry_b3 PARTITION OF device_telemetry FOR VALUES WITH (MODULUS 4, REMAINDER 3);
Verifying partition pruning with EXPLAIN ANALYZE
Partition pruning is the performance engine behind partitioned tables. When you query the table, the query planner checks whether the WHERE clause eliminates partitions from execution. Learn how to inspect query execution trees in our guide to reading PostgreSQL EXPLAIN ANALYZE.
Inspecting partition pruning in EXPLAIN plans
EXPLAIN (ANALYZE, COSTS OFF)SELECT * FROM audit_logsWHERE created_at >= '2026-10-15' AND created_at < '2026-10-20';-- Result demonstrates only one partition is scanned:-- Append (actual time=0.045..0.089 rows=14 loops=1)-- -> Seq Scan on audit_logs_2026_10 (actual time=0.044..0.086 rows=14 loops=1)-- Filter: ((created_at >= '2026-10-15') AND (created_at < '2026-10-20'))
According to the PostgreSQL runtime query configuration, partition pruning is governed by enable_partition_pruning = on. Pruning occurs at plan time for constant values and at execution time for parameterized queries and subqueries.
Dropping and detaching partitions for zero-downtime data lifecycle
In non-partitioned tables, deleting old rows requires DELETE FROM table WHERE date < now() - INTERVAL '1 year'. This generates massive transaction log volume, triggers autovacuum bloat, and locks rows. On a partitioned table, deleting an entire month of historical data is instantaneous and costs zero I/O.
Instant data purge via drop partition
-- Method 1: Detach partition first for safe archivingALTER TABLE audit_logs DETACH PARTITION audit_logs_2026_10 CONCURRENTLY;-- Back up the standalone table audit_logs_2026_10 if needed...-- Method 2: Drop partition directly (instant metadata operation)DROP TABLE audit_logs_2026_10;
Actionable checklist for PostgreSQL table partitioning
Include the partition key in all primary key and unique constraints.
Choose partition intervals matching query patterns (typically monthly or weekly for time-series).
Create upcoming partitions in advance via cron jobs or pg_partman extension.
Verify partition pruning with EXPLAIN ANALYZE on realistic query filters.
Create a DEFAULT partition for list-based schemas to prevent insert rejections.
Use DETACH PARTITION CONCURRENTLY to retire old partitions without blocking table reads.
Monitor total partition count: avoid creating thousands of small partitions to prevent planner overhead.
Wrapping up
PostgreSQL declarative partitioning simplifies time-series data management, speeds up queries through partition pruning, and allows instant data retirement. Before applying partition migrations to production schemas, format your DDL statements with sqlfmt to guarantee clear, consistent SQL code across your engineering organization.