PostgreSQL table partitioning

A plan for choosing range, list or hash partitioning on large PostgreSQL tables, with the query, retention and constraint trade-offs to settle before the schema is built.

On this page

When PostgreSQL table partitioning fits a large table

If a large table is slow to query, expensive to purge or growing without limit, declarative partitioning may help. It splits one logical table into physical partitions that the planner can prune, so a query that filters on the partition key reads only the partitions it needs. Whether it helps depends on two decisions: the partition key and the partitioning method (range, list or hash). A poor key gives no pruning and adds planning overhead without saving any reads.

Partitioning is a schema decision. The partitioned table's primary key and unique constraints must include the partition key, so a table that enforces uniqueness on an identifier alone usually needs redesigning before it can be partitioned. Foreign keys that reference or are referenced by a partitioned table also carry restrictions. Converting an existing monolithic table means copying data, rebuilding indexes and changing application queries, which is why teams should decide before the table reaches its size problem. Check the current PostgreSQL partitioning limitations in the official documentation against the server version you plan to run.

Before committing, measure what the table actually does. Confirm that most slow queries filter on one column that maps cleanly to ranges, categories or hash buckets, and that retention is performed by row age. If the workload is dominated by lookups on a random key with no time or category filter, partitioning will add complexity without a clear benefit. A reviewer should be able to name the partition key, the expected partition count and the retention rule in writing before any build starts.

Range, list and hash partitioning compared

This table compares the three declarative partitioning methods on the key they need, the workloads they suit, how pruning applies and the pitfalls that show up later. Read each row against your table's access pattern and retention rule, then choose the method that matches the most frequent filter or the largest operational task.

MethodPartition key and fitHow pruning worksMain pitfalls
RangeOrdered values such as timestamps or IDs. Fits time-based data where old partitions are dropped for retention.Queries with a filter on the key range scan only matching partitions. Filters on other columns scan all partitions.Uneven partition sizes if data arrives unevenly. New partitions must be created ahead of inserts, or rows fail to route.
ListDiscrete values such as region, country or tenant group. Fits categorical data with a known, fairly stable set of values.Equality or IN filters on the listed values touch only the matching partitions.Rows with values not assigned to any partition are rejected unless a default partition exists. Adding values means creating new partitions.
HashA modulus and remainder over the key. Fits even spread of write load when no natural range or category exists.Equality filters on the key touch one partition. Range filters on the key usually scan all partitions.Gives no retention benefit, since data is not grouped by time or category. Changing the partition count later is an offline-style migration to plan.
Primary key and unique constraintsEvery unique or primary key must include all partition key columns.Not applicable. Constraints are enforced per partition, so the key shape limits what can be declared.Teams often add a surrogate key alone and find the declaration fails. Confirm the exact rules in the current partitioning documentation before finalizing the schema.
Retention by dropping partitionsWorks best with range partitions on a time column aligned to the retention period.Dropping or detaching a partition avoids a bulk DELETE and the vacuum work that follows it.Queries that span the retention boundary still need care. Confirm detach and drop behavior for your version.
Partition countEach partition adds catalog entries, planning work and maintenance objects.The planner must consider more partitions when pruning cannot exclude them.Hundreds of partitions can slow planning. Ask for a measured plan time on representative queries before choosing a granularity.
Multi-level (sub-partitioning)Combining methods, such as range then list, adds another key layer.Pruning depends on filters at each level. Confirm current support and planner behavior in the PostgreSQL documentation for your version.Each added level multiplies partition count and complicates constraint and index design. Treat as a design to validate, not a default.

How inserts and queries reach the right partition

The diagram starts with an insert or query against the parent table, which owns no rows itself. On insert, the partition key value decides which child partition receives the row, and rows that match no defined range or list fall into a default partition if one exists. On a query, the planner compares the WHERE clause with each partition's bounds and skips partitions that cannot match. Check that your most common filters use the partition key directly, because a filter that wraps the key in a function or omits it usually prevents pruning.

Routing of inserts and pruning of queries across partitions.

Why primary keys and unique constraints must include the partition key

On a partitioned table, PostgreSQL enforces uniqueness only within each partition, so the partition key has to be part of every unique index and primary key. These rules shape key design, foreign keys and migration planning, and each one should be checked against the current partitioning documentation for your PostgreSQL version.

Partition key in every unique index

A primary key or unique constraint on a partitioned table must include all partition key columns. A single-column key such as id alone is rejected, because each partition holds its own index and uniqueness cannot be checked across partitions without the key. Confirm the exact rule for your version before you finalize the schema, and list every unique index, including those created by UNIQUE clauses in migrations. Expect to change key definitions, not only indexes.

Partitioning docs

Composite keys change application contracts

Once the key becomes (tenant_id, id) or (created_at, id), every lookup, foreign key target and ORM mapping that assumed a single-column identifier needs review. Application code that fetches a row by id alone may now scan several partitions. Check ORM identity maps, API identifiers and any code that treats the primary key as a single value.

Foreign keys into partitioned tables

A foreign key that references a partitioned table must point at a unique constraint that includes the partition key, which pushes child tables to carry the partition key columns too. Foreign keys from a partitioned table to another table are also restricted in some versions. Map every inbound and outbound reference before you partition, because a missing column can force a schema redesign late in the project.

Identity and UUID columns

Identity columns and uuidv7() defaults still generate unique values, but they do not remove the need for the partition key in the constraint. A time-ordered UUID often works well with a range key on creation time, which keeps the key meaningful for both uniqueness and pruning. Confirm whether your identity sequence and default expressions behave as expected after the table is partitioned, and decide whether sequence values should be unique globally or only per partition.

Check existing constraints before migrating

Before converting an unpartitioned table, inventory every primary key, unique index, foreign key, check constraint and exclusion constraint. Record which ones omit the intended partition key, and decide whether each should be redesigned or dropped and replaced by an application or trigger check. Test the conversion on a copy with production-sized data, since the rebuild can take a long time and needs a rollback plan.

Validate duplicate rules with tests

Write tests that insert duplicate business keys into different partitions and confirm the database and application both reject or handle them as intended. Include cases where the partition key changes on update, since moving a row between partitions can conflict with uniqueness rules. Keep these tests in the migration pipeline so later schema changes cannot silently remove the partition key from a constraint.

How to plan and build a partitioned table safely

This sequence takes a large PostgreSQL table from workload analysis to a partitioned layout that prunes queries, supports fast retention, and runs its partition management on a schedule. Each step closes with a check you can run before moving on.

  1. Confirm query patterns and retention rules

    Start by listing the top queries against the table, the filters they use, and how long rows must be kept under your retention policy. Record which columns appear in WHERE clauses and which rows are deleted in bulk, because those answers decide whether partitioning helps at all. Involve the application owners and the team that signs off on retention, since they own the rules. Done means you have a written list of queries with their filter columns and a retention period agreed in writing, along with an estimate of how the table grows over time. If most queries do not filter on one column, partitioning may add cost without a gain, so record that finding too.

  2. Choose the partition method and key

    Select range, list or hash partitioning based on the filter pattern from the first step. Range suits time-based retention and date filters, list suits a small fixed set of values such as region, and hash spreads rows evenly when no natural range exists and only equality lookups matter. The partition key must appear in every unique or primary key on the parent table, so choose a key that your uniqueness rules can accept. Done means a short design note names the method, the key, and the reason, and the application team has reviewed it. Check that the key is present in the columns used by your most common lookups.

  3. Define the partitioned parent table

    Create the parent table with PARTITION BY and the chosen key, using the same column definitions the application expects. The parent holds no rows itself, so queries, grants and constraints you define here apply to the whole set of partitions. Keep primary keys and unique constraints on the parent only where they include the partition key, and document any constraint that cannot be enforced across partitions. Done means the parent exists in a staging database, \d+ shows the partition key and strategy, and the team has confirmed which constraints are enforced at the parent level.

  4. Create partitions and a default partition

    Create the initial child partitions covering the existing data range and a few future ranges, or the agreed list values or hash remainders. Add a DEFAULT partition to catch rows that match no other partition, and monitor it so unexpected values do not accumulate there silently. Name partitions consistently so scripts can find them. Done means every existing row falls into a named partition, a test insert outside all ranges lands in the default partition, and you can list the partitions with a query against the catalog.

  5. Add indexes to each partition

    Create the indexes your query patterns need on the parent so PostgreSQL propagates them to every partition, then check that each partition has the expected index. Indexes on a partitioned table are built per partition, so large partitions take time to index, and that work should be scheduled in a maintenance window. Use concurrent index creation on existing partitions where your PostgreSQL version and workload allow it. Done means \d on sample partitions shows the same indexes as the parent, and the index list is recorded in your migration runbook.

  6. Migrate data in batches

    Move rows from the original table into the partitioned table in ranges, committing each batch so locks stay short and replication lag stays visible. Verify row counts and checksums per range against the source before switching the application. Plan the cutover with the application team, including how writes that land during the copy are captured, either by a short write freeze or by a sync step. Done means source and target counts match for every range, the application reads and writes through the new table in a test environment, and the rollback path has been rehearsed.

  7. Verify partition pruning with EXPLAIN

    Run the top queries from the first step with EXPLAIN and confirm that the plan lists only the partitions the filter needs. Pruning depends on the filter matching the partition key with a compatible type and expression, so a function wrapped around the key can stop it. Check both static pruning in the plan and runtime pruning for parameterized queries. Done means each top query scans the expected partitions in the plan, and any query that scans all partitions is either fixed or documented as an accepted cost.

  8. Automate partition creation and detachment

    Schedule a job that creates future partitions before they are needed and, where retention applies, detaches or drops partitions that are older than the retention period. Detaching first keeps the old data available for checking before removal, while dropping is the fast retention path. Test the job against a copy of production, and alert when the default partition holds rows or when the next partition is missing. Done means the job runs in staging through a full retention cycle, its failures raise an alert, and the team can show a detached partition was archived or dropped as the policy requires.

How dropping partitions speeds retention and where it breaks

The main reason to partition a large table for retention is that removing old data becomes a catalog operation instead of a bulk write. Detaching a partition with ALTER TABLE ... DETACH PARTITION and then dropping it removes its rows without scanning them row by row, so it avoids the long DELETE that would otherwise generate dead tuples across the whole table. The cost does not disappear entirely. Dropping a partition frees its files at once, but the retention job itself should be tested in staging against a copy of production volume, because detaching a partition that still has active sessions or foreign keys referencing it can block or fail. Confirm the locking behavior of your PostgreSQL version and plan the job for a low-traffic window, and decide whether detached partitions are archived (for example with pg_dump of that table) before the drop.

Partition pruning is the read-side benefit. The planner excludes partitions that cannot contain matching rows, but only when the query filter compares the partition key directly against constants, parameters or expressions the planner can evaluate. Pruning does not happen when the predicate omits the key, when the key is wrapped in a function (for example date_trunc('month', created_at) = ... on a table partitioned by created_at), or when a cast or operator changes the comparison type. In those cases every partition is scanned. Review the top queries with EXPLAIN and look for the partitions listed under the plan rather than assuming pruning occurred. The usual fix is to rewrite the filter as a range on the raw column, and to make sure application code and reporting tools follow that pattern, since a single unpruned dashboard query can negate the design.

How many partitions is too many

Partitioning looks simple until the partition count climbs. The costs below grow with the number of partitions, not with the data, so they are easy to miss in a test with a few partitions. Check each one against your own workload and PostgreSQL version before settling on a layout.

Planner overhead grows with partition count

The planner must consider every partition that a query could touch, and pruning only helps when it can exclude partitions early. Queries that filter on the partition key at execution time, or that lack a usable predicate, can spend noticeable time planning across hundreds of children. Measure planning time with EXPLAIN on representative queries as you add partitions, and confirm where it starts to rise for your workload and PostgreSQL version.

Read the docs

Catalog and memory cost per partition

Each partition is a relation with its own entries in the system catalogs, indexes, statistics and per-backend relation cache. Every backend that touches a partitioned table loads metadata for the partitions it uses, so memory use grows with both partition count and connection count. Check catalog size and backend memory under peak connections, and confirm the limits your PostgreSQL version and connection pooling layer can handle.

Operational load of creating and monitoring partitions

Someone or something must create future partitions before data arrives, detach and drop old ones on schedule, and verify that each partition has the expected indexes and constraints. Without automation, a missed partition means inserts fail or land in the wrong place. Plan who owns the job, how failures alert, and how the process runs during a deployment or a restore.

Lock behavior during attach and detach

ATTACH PARTITION and DETACH PARTITION take locks that can block queries on the parent table. Attaching a partition also requires a scan to validate the partition constraint unless a matching CHECK constraint already exists, which can take time on large tables. Test these operations on a copy of production volumes, use the non-blocking detach option where your version supports it, and schedule the work in a window your application can tolerate.

Default partition can hide routing gaps

A DEFAULT partition accepts rows that match no other partition, which prevents insert errors when a new range or list value appears. The cost is that rows can pile up there silently, and moving them later means scanning the default partition while creating new ones. Monitor row counts in the default partition, alert when it is not empty, and confirm how your version handles adding a partition that overlaps existing default rows.

Questions teams ask before partitioning a PostgreSQL table

What does partitioning a PostgreSQL table cost, and who does the work?

The cost is mostly engineering time, split between schema design, the migration of existing rows, application query review and testing. Your team pays for its own staff time whether or not it hires help, and a partner's fee follows from a written scope that lists the tables, the partition strategy and the deliverables. Partitioning itself is a built-in PostgreSQL feature with no license fee, so the recurring costs are the infrastructure you already run plus ongoing partition maintenance, such as creating future partitions and dropping expired ones. Ask any quote to separate one-time design and migration work from recurring operations.

How long does a partitioning migration take, and what drives the duration?

Duration depends mainly on table size, write volume, and how much the application must change. Moving rows from an existing table into partitions copies data, so large tables need a window or a strategy that keeps writes flowing while the copy runs. The number of dependent objects matters too: foreign keys, triggers, indexes, views and application queries that reference the table all need review. Ask for a plan that states how the cutover happens, how rollback works, and what is measured before go-live. Without a supplied benchmark, treat any duration quoted to you as unverified until it is tested against a copy of your data.

What does our internal team need to provide?

Your team needs to supply knowledge of the table's access patterns, retention rules and write volume, plus access to a staging environment with production-like data. Engineers who own the queries should identify which predicates filter on the chosen partition key, because partition pruning only helps when queries include that key. Someone must also own the operational routine: who creates new partitions before data arrives, who drops old ones, and who monitors the default partition. Agree these responsibilities before the build starts, or the first missed partition will surface as an insert error in production.

Can our team partition a table without outside help?

A capable PostgreSQL team can do it alone if it has tested the migration on realistic data, reviewed every constraint that involves the partition key, and written the maintenance job. The risky parts are primary and unique keys, which must include the partition key, and foreign keys that point at or from a partitioned table, which need careful checking against your PostgreSQL version. Teams often choose outside help when the table is business-critical, the migration cannot tolerate a long write freeze, or nobody has done a partition cutover before. Ask a partner to show which parts of the work it would hand back to your staff.

How does partitioning differ from sharding?

Partitioning splits one logical table into pieces inside a single PostgreSQL cluster, and the database planner decides which pieces a query touches. Sharding spreads data across separate database servers, and the application or a routing layer decides where each row lives. Partitioning helps with table size, index maintenance and fast deletion of old data, but it does not add write capacity beyond one server. Sharding adds that capacity at the cost of cross-shard queries, distributed transactions and much harder operations. Most teams should exhaust partitioning, indexing and hardware options on one cluster before considering sharding.

When should we avoid partitioning a table?

Avoid partitioning when the table is small, when queries rarely filter on a single natural key, or when the main problem is slow queries that a better index would solve. Too many partitions also hurt planning time and memory use, so a design that creates thousands of small partitions can be slower than the original table. If the partition key would have to be added to every unique constraint in a way that breaks business rules, the design needs rethinking. Measure first with the query workload and table statistics, and make the decision on those numbers rather than on the size of the table alone.

How does partitioning interact with PostgreSQL major upgrades?

Partitioned tables upgrade like other tables, whether you use pg_upgrade or logical replication, but the upgrade plan must account for the partition layout and the publication or subscription setup if you replicate. Logical replication handles partitioned tables only when the publication settings match what you intend to replicate, so test that path on your version pair. Check the upgrade documentation for the source and target versions you plan to use, and rehearse the full sequence, including the maintenance job that creates new partitions during the cutover window. Also confirm that planner statistics behave as expected after the upgrade, which you should verify in your own test environment.

How DeployOpen scopes and delivers partitioning work

DeployOpen plans, implements, tests, documents and supports self-hosted PostgreSQL inside your own infrastructure. For table partitioning, that means starting from your query patterns and retention rules, building the partition layout against a written scope, and handing over a design your team can operate after the engagement ends.

How we scope

  • Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.
  • The written scope names the tables, partition key, partitioning type and the queries that must prune partitions.
  • Scope also lists retention rules, the partition creation and removal jobs, and which unique constraints must include the partition key.

How we build

  • We build the partitioned tables in a non-production copy of your data and measure plans with representative queries.
  • Default partitions, pre-created future partitions and partition maintenance jobs are configured and tested before any cutover.
  • Migration of existing tables onto partitions is rehearsed, including locking behavior and rollback steps, against a copy of production.

How we hand over

  • You receive the partition design, key and constraint decisions, and the reasons behind each one in written form.
  • Runbooks cover adding partitions, detaching and dropping old partitions, and checking that pruning still works after schema changes.
  • Your team is walked through the maintenance jobs, alert conditions and the review steps for changes to the partition scheme.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers after handover.
  • Support can cover PostgreSQL major version upgrades, which retain partitioned table definitions when planned with the upgrade method you choose.
  • Confirm with us during scoping which monitoring, backup and restore checks must be re-verified after partition changes.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.