Skip to content

    System Design

    Table Partitioning: Range, List and Hash With PostgreSQL

    Learn range, list and hash partitioning, how partition pruning shows up in EXPLAIN, and how attach and detach work, with a lab on in-process PostgreSQL.

    By Published 13 min read

    Share

    Standard lessonintermediatePostgreSQL labBackend System Design

    Before this: SQL Indexing: B-Trees, Composite, Covering and Partial Indexes

    What you'll learn: By the end of this lesson you will be able to explain what table partitioning is and what it is not, choose between range, list and hash partitioning, read partition pruning in EXPLAIN output and say when it cannot happen, state the rule that unique keys must contain the partition key, run attach and detach as a retention routine, and name what an in-process PostgreSQL lab can and cannot show about all of it.

    Imagine one huge drawer holding every receipt a company has ever issued. To find last March's receipts you flip through years of paper, and to throw away 2019 you shred each sheet. Now give each month its own drawer. Finding March means opening one drawer, and throwing away 2019 means carrying twelve drawers to the bin.

    Table partitioning does that inside a database. One logical table is stored as several physical tables, chosen by the value of a key, so queries can skip drawers and maintenance can remove whole drawers. It is not sharding: all partitions still live in one database server, which the sharding lesson contrasts with splitting data across servers. The B-tree indexes inside each partition are their own lesson; this one covers how partitions change what the planner and the operator can do.

    Verified on 2026-12-01 against the PostgreSQL 18 manual (Table Partitioning, CREATE TABLE, ALTER TABLE, ANALYZE) and the PGlite documentation. Lab output comes from the PostgreSQL 19.0 build inside PGlite 0.6.1, while the course targets PostgreSQL 18: behaviours are stated from the 18 pages and the lab confirms them on the build it ran on.

    The core idea

    Partitioning splits one logical table into pieces by a key, so the planner can prove most pieces irrelevant to a query and the operator can add or drop whole pieces instead of rows. The manual describes a partitioned table as "a 'virtual' table having no storage of its own"; the storage belongs to the partitions, "which are otherwise-ordinary tables".

    Three labelled illustrations run through the lesson: a minimal example (three monthly partitions of an orders table in the lab), a realistic example (ShopStream's orders retention) and a failure example (an insert on the first of the month with no partition ready).

    The manual lists the benefits: faster queries "in certain situations, particularly when most of the heavily accessed rows of the table are in a single partition or a small number of partitions"; bulk loads and deletes "by adding or removing partitions"; and dropping or detaching a partition "is far faster than a bulk operation" and avoids the VACUUM overhead of a bulk DELETE. All depend on how the table is queried and maintained: partitioning a table whose queries never mention the key helps nothing.

    Range, list and hash

    The manual defines three forms:

    Form Rule Typical key Weak point
    Range Ranges of a key, no overlap; the lower bound is inclusive, the upper bound exclusive A date You must create the next range before data arrives
    List Each partition lists the key values it holds A region or tenant One value cannot be split across partitions
    Hash A modulus and remainder per partition; the hash of the key picks the partition An id with many values Neighbouring keys land in different partitions, so range queries touch all of them

    The CREATE TABLE page adds that list partitioning takes a single column, MINVALUE and MAXVALUE mean "no lower or upper bound", a DEFAULT partition catches "a partition key value not fitting into any other partition" (not available for hash), and "if no existing partition matches the values in the new row, an error will be reported".

    One logical orders table stored as monthly partitionsCheckout to orders (one table name); orders to orders_2026_01 (routes by date); orders to orders_2026_02; orders to orders_2026_03Checkout: reads and writesCheckoutreads and writesorders: partitioned, no rowsorderspartitioned, norowsorders_2026_01: Januaryorders_2026_01Januaryorders_2026_02: Februaryorders_2026_02Februaryorders_2026_03: Marchorders_2026_03Marchone table nameroutes by date

    Figure 1. A range-partitioned table. How to read this: the application sees one table. The parent routes each row to the partition whose range holds its date, and a query on a date range can be answered from one partition.

    flowchart TD accTitle: Choosing a partitioning form accDescr: A decision flow. If rows age out or are loaded by a date or other ordered key, use range partitioning. If data splits into a few named groups such as regions, use list partitioning. If neither applies and you want an even spread by an id with many values, use hash partitioning, accepting that range queries touch every partition. If queries do not filter on any one key, do not partition. S["What drives the table's queries and upkeep?"] --> A{"Rows age out or load
    by an ordered key?"} A -->|yes| R["Range, for example by month"] A -->|no| B{"A few named groups
    such as regions?"} B -->|yes| L["List"] B -->|no| C{"Queries filter on one id
    and you want an even spread?"} C -->|yes| H["Hash, but range queries touch all partitions"] C -->|no| N["Do not partition"]

    Figure 2. Choosing a form. How to read this: start from what you need to make cheap. Range follows ordered keys and retention, list follows named groups, hash buys spread at the cost of range queries.

    Declaring it

    This is the lab's setup, trimmed to the essentials (the lab runs it in full):

    create table orders_p (
      id int not null, shopper_id int not null,
      order_date date not null, total_cents int not null,
      primary key (id, order_date)
    ) partition by range (order_date);
    create table orders_2026_02 partition of orders_p
      for values from ('2026-02-01') to ('2026-03-01');
    create index on orders_p (shopper_id);

    The create index on the parent creates a matching index on every partition.

    Partition pruning

    Pruning is the planner dropping partitions it can prove a query cannot need. The manual's example: without it a query "would scan each of the partitions"; with it, "the planner will examine the definition of each partition and prove that the partition need not be scanned because it could not contain any rows meeting the query's WHERE clause". It is controlled by enable_partition_pruning.

    Pruning "is driven only by the constraints defined implicitly by the partition keys, not by the presence of indexes", so the key needs no index of its own. The planner must be able to compare the WHERE clause with the bounds, which is why the manual advises that the best key is often "the column or set of columns which most commonly appear in WHERE clauses". Pruning can also happen during execution, for example for PREPARE parameters or a subquery value; the lab does not exercise that case.

    flowchart TD accTitle: How the planner treats a filter on a partitioned table accDescr: If the WHERE clause compares the bare partition key with constants or parameters, the planner keeps only partitions whose bounds could match. If the filter does not mention the key, or wraps the key in a function, every partition is scanned and each partition's own indexes are used. Q["Query on the partitioned table"] --> K{"WHERE compares the bare
    partition key?"} K -->|yes| P["Keep only partitions whose
    bounds can match"] K -->|"no, or key inside a function"| A["Scan every partition
    using each partition's indexes"] P --> I["Use the surviving partition's index if it helps"]

    Figure 3. When pruning happens. How to read this: the test is whether the planner can compare the key itself with the bounds. Everything else takes the right-hand branch, whose cost grows with the number of partitions.

    Keys, constraints and how many partitions

    The manual's limitation is easy to miss: "the constraint's columns must include all of the partition key columns" for a unique or primary key, because each partition's index "can only directly enforce uniqueness within their own partitions". So primary key (id, order_date) is allowed, primary key (id) is not, and the same id with a different date is a different key. For global uniqueness of an id, generate unique ids (see unique ID generation) instead of expecting the database to enforce it across partitions.

    How many partitions is a trade-off. The manual says too few "may mean that indexes remain too large and that data locality remains poor", while too many "can mean longer query planning times and higher memory consumption", that the planner copes with "up to a few thousand partitions fairly well, provided that typical queries allow the query planner to prune all but a small number", and it ends: "Never just assume that more partitions are better than fewer partitions, nor vice-versa."

    Statistics need care. The ANALYZE page says the autovacuum daemon "does not process partitioned tables", so "it is usually necessary to periodically run a manual ANALYZE to keep the statistics of the table hierarchy up to date".

    Maintenance: attach, detach, drop

    This is where partitioning pays for itself: create the next partition ahead of time and retire the oldest.

    • Drop a partition with DROP TABLE. The manual says this "can very quickly delete millions of records", and requires an ACCESS EXCLUSIVE lock on the parent.
    • Detach with ALTER TABLE ... DETACH PARTITION to keep the data as an ordinary table first. The plain form needs an ACCESS EXCLUSIVE lock on the parent; with CONCURRENTLY it needs only SHARE UPDATE EXCLUSIVE on the parent. That form "cannot be run in a transaction block and is not allowed if the partitioned table contains a default partition", and it works in two internal transactions, waiting for other users of the table.
    • Attach a prepared table with ATTACH PARTITION. It takes SHARE UPDATE EXCLUSIVE on the parent, "in addition to the ACCESS EXCLUSIVE locks on the table being attached and on the default partition (if any)". Unless a valid CHECK constraint already proves the rows fit, "a full table scan is performed" to validate them, so the manual recommends adding a matching CHECK first and dropping it afterwards.
    • The default partition interferes. Adding a partition means scanning the default partition for rows that belong in the new one, unless a constraint on the default proves there are none.
    sequenceDiagram accTitle: Monthly retention routine for a partitioned table accDescr: A scheduled job first creates and loads a standalone table with a CHECK constraint, attaches it as next month's partition, then detaches the oldest partition concurrently, archives its data, and drops it. participant J as Scheduled job participant P as Parent table participant N as New table participant O as Oldest partition J->>N: create, load, add CHECK matching the range J->>P: ATTACH PARTITION N J->>P: DETACH PARTITION O CONCURRENTLY J->>O: archive its rows J->>O: DROP TABLE

    Figure 4. A monthly retention routine. How to read this: time runs downward. The attach comes before the month starts, the detach after retention ends, and each step touches one partition.

    Build it: partitioning on PGlite

    Setup. The lab is examples/postgres-labs/labs/table-partitioning/, 3,000 illustrative orders over three months. It runs on PGlite, which the documentation says has "a single exclusive connection to the database". So the lab shows plan shapes, routing and lock modes, and cannot show:

    • how long an attach or detach holds its locks, or other sessions waiting behind them;
    • whether an attach scanned the table (the scan is invisible in the output; that rests on the manual);
    • run-time pruning with parameters, planning time with thousands of partitions, or any timing.
    cd examples/postgres-labs
    npm install
    node --test labs/table-partitioning/test.mjs
    node labs/table-partitioning/run.mjs

    Expected output, captured from a real run (the partitions and where the rows went, PostgreSQL 19.0 in PGlite 0.6.1):

    orders_2026_01: FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')
    orders_2026_02: FOR VALUES FROM ('2026-02-01') TO ('2026-03-01')
    orders_2026_03: FOR VALUES FROM ('2026-03-01') TO ('2026-04-01')
    rows in orders_2026_01: 1053
    rows in orders_2026_02: 924
    rows in orders_2026_03: 1023
    rows in the parent table itself (no storage of its own): 0
    CREATE INDEX ON the parent created 3 per-partition shopper_id indexes

    The parent holds no rows, and one CREATE INDEX on it made one index per partition.

    Expected output, captured from a real run (pruning, queries A to C: a one-month filter, EXPLAIN ANALYZE and a date on a bound):

    A. filter on the partition key, one month:
        Aggregate
          ->  Seq Scan on orders_2026_02 orders_p
                Filter: ((order_date >= '2026-02-01'::date) AND (order_date < '2026-03-01'::date))
    B. same query, EXPLAIN ANALYZE (actual rows):
        Aggregate (actual rows=1.00 loops=1)
          ->  Seq Scan on orders_2026_02 orders_p (actual rows=924.00 loops=1)
                Filter: ((order_date >= '2026-02-01'::date) AND (order_date < '2026-03-01'::date))
    C. a date that sits on a bound (upper bounds are exclusive, so 2026-03-01 is in March):
        Aggregate
          ->  Seq Scan on orders_2026_03 orders_p
                Filter: (order_date = '2026-03-01'::date)

    Only orders_2026_02 appears for the one-month filter, and EXPLAIN ANALYZE shows 924 rows read. 2026-03-01 is in March because February's upper bound is exclusive.

    Expected output, captured from a real run (query D, a filter on shopper_id only):

    D. filter on shopper_id only (not the partition key):
        Aggregate
          ->  Append
                ->  Bitmap Heap Scan on orders_2026_01 orders_p_1
                      Recheck Cond: (shopper_id = 7)
                      ->  Bitmap Index Scan on orders_2026_01_shopper_id_idx
                            Index Cond: (shopper_id = 7)
                ->  Bitmap Heap Scan on orders_2026_02 orders_p_2
                      Recheck Cond: (shopper_id = 7)
                      ->  Bitmap Index Scan on orders_2026_02_shopper_id_idx
                            Index Cond: (shopper_id = 7)
                ->  Bitmap Heap Scan on orders_2026_03 orders_p_3
                      Recheck Cond: (shopper_id = 7)
                      ->  Bitmap Index Scan on orders_2026_03_shopper_id_idx
                            Index Cond: (shopper_id = 7)

    Every partition appears, each with its own index scan: the index helps inside a partition but cannot let the planner skip one.

    Expected output, captured from a real run (queries E and F: the key inside a function, then pruning switched off):

    E. the key wrapped in a function:
        Aggregate
          ->  Append
                ->  Seq Scan on orders_2026_01 orders_p_1
                      Filter: (EXTRACT(month FROM order_date) = '2'::numeric)
                ->  Seq Scan on orders_2026_02 orders_p_2
                      Filter: (EXTRACT(month FROM order_date) = '2'::numeric)
                ->  Seq Scan on orders_2026_03 orders_p_3
                      Filter: (EXTRACT(month FROM order_date) = '2'::numeric)
    F. query A again with enable_partition_pruning = off:
        Aggregate
          ->  Append
                ->  Seq Scan on orders_2026_01 orders_p_1
                      Filter: ((order_date >= '2026-02-01'::date) AND (order_date < '2026-03-01'::date))
                ->  Seq Scan on orders_2026_02 orders_p_2
                      Filter: ((order_date >= '2026-02-01'::date) AND (order_date < '2026-03-01'::date))
                ->  Seq Scan on orders_2026_03 orders_p_3
                      Filter: ((order_date >= '2026-02-01'::date) AND (order_date < '2026-03-01'::date))

    Wrapping order_date in EXTRACT stops pruning in this lab, and switching enable_partition_pruning off gives the all-partitions plan for a query that pruned before. Query G in the demo combines a key range with shopper_id: it prunes to one partition and then uses its index.

    Expected output, captured from a real run (routing errors and the unique-key rule):

    insert dated 2026-04-15 with no matching partition: no partition of relation "orders_p" found for row
    after CREATE TABLE orders_default PARTITION OF orders_p DEFAULT: the row lands in orders_default
    CREATE UNIQUE INDEX ON orders_p (id): UNIQUE constraint on partitioned table must include all partitioning columns
    same id 1 inserted with a different order_date (primary key is id, order_date): accepted

    The first line is the failure example: an insert with no partition fails until a partition or a default exists. The third is the manual's rule enforced, and the fourth its consequence: id 1 is accepted again with a different date.

    Expected output, captured from a real run (attach: the default-partition clash, then the locks of a successful attach):

    attach while orders_default still holds an April row: updated partition constraint for default partition "orders_default" would be violated by some row
    moved that row into orders_2026_04 and deleted it from orders_default
    locks held on tables inside the ATTACH transaction:
        orders_2026_04: AccessExclusiveLock
        orders_2026_04: ShareLock
        orders_default: AccessExclusiveLock
        orders_p: ShareUpdateExclusiveLock

    The attach first failed because orders_default held an April row; after the row moved it succeeded, with SHARE UPDATE EXCLUSIVE on the parent and ACCESS EXCLUSIVE on the new table and the default partition, as the manual states. The extra SHARE lock on the new table is the lab's own observation.

    Expected output, captured from a real run (detach locks and the restrictions on CONCURRENTLY):

    locks held inside a plain DETACH PARTITION transaction (rolled back):
        orders_2026_01: AccessExclusiveLock
        orders_default: AccessExclusiveLock
        orders_p: AccessExclusiveLock
    DETACH ... CONCURRENTLY inside a transaction block: ALTER TABLE ... DETACH CONCURRENTLY cannot run inside a transaction block
    DETACH ... CONCURRENTLY while a default partition exists: cannot detach partitions concurrently when a default partition exists
    after DETACH PARTITION: orders_2026_01 is a stand-alone table with 1053 rows; orders_p now has 2248 rows
    dropped the detached table (archive it first if you need the data)
    
    == 6. DETACH PARTITION CONCURRENTLY on a partitioned table without a default partition
    DETACH ... CONCURRENTLY outside a transaction block: ok
    audit_p rows before: 200, after: 84; audit_2026_01 still a partition: false

    A plain detach took ACCESS EXCLUSIVE on the parent, as the manual says. CONCURRENTLY is refused inside a transaction block and while a default partition exists, and succeeded on a table without one. The lock on orders_default during a plain detach is another observation the pages do not describe.

    Expected output, captured from a real run (hash partitioning with modulus 4, then one shopper):

    rows in orders_h0: 855
    rows in orders_h1: 765
    rows in orders_h2: 840
    rows in orders_h3: 540
    one shopper:
        Aggregate
          ->  Seq Scan on orders_h3 orders_h
                Filter: (shopper_id = 7)

    Equality on the hash key prunes to one partition. The counts are uneven because there are only 200 distinct shoppers, and the demo's range-of-shoppers query scans all four partitions because hash order is not key order.

    Break it. In lab.mjs, change query E's filter to a plain date range on order_date and compare the plan. Restore the file and re-run the tests.

    Trade-offs: partitioning and its alternatives

    Approach Gain Cost Wrong when
    One table with the right indexes Simplest Bulk deletes and big-table maintenance stay hard Retention or archiving is a regular job
    Partitioning in one database Pruning; cheap drop and attach Key must lead queries; unique keys must include it; a partition-creation job to own Queries rarely filter on one key
    Sharding across servers Scales writes and storage past one server Cross-shard queries and operations One server is enough
    Separate archive table Easy to reason about Application must know which table to read You want one query surface

    In practice: ShopStream's orders retention

    This is a realistic scenario, not a case history. Every number is illustrative.

    The situation

    ShopStream targets 500,000 orders per day, about 15 million rows per 30-day month. Support queries look at recent weeks, finance reports at one month, and policy keeps 13 months online. A plain DELETE of the oldest month leaves millions of dead row versions for VACUUM.

    Starting architecture

    A single orders table with indexes on shopper and date, on one primary database. A nightly job deletes rows older than 13 months.

    Options considered

    • Keep DELETE. No schema change, but the cost is the one the manual names.
    • Monthly range partitions on order_date. Support and finance queries already filter on date, so they prune; retention becomes detach and drop.
    • Hash partitions by shopper. Spreads load, but retention and date reports touch every partition.

    The decision

    Monthly range partitions, with the next two months created ahead of time by a scheduled job that also alerts when fewer than two future partitions exist. Primary key (id, order_date), and ids from a unique generator. A default partition is not used, because it blocks DETACH ... CONCURRENTLY and scans on attach.

    Rollout and verification

    Build the partitioned table beside the old one and move data in batches, using the schema-evolution lesson's pattern. Verify by reading plans: support and finance queries must show only the partitions they need, and any query without a date will scan every partition.

    The 2 a.m. failure

    At midnight on the first of the month, checkouts fail with no partition of relation "orders" found for row. The scheduled job had been failing silently for two weeks, so the next partition did not exist. The lab prints this exact error for a date with no partition.

    Checks: confirm the error in the logs, list the partitions and bounds from the catalog, and check the job's history. Mitigation: create the missing partition at once. Lasting fix: the alert on future partitions. A default partition would hide the problem and make later attaches slower and concurrent detach unavailable.

    Architect's notes

    • Partition for an operation you run. Retention and bulk load justify it; speculation does not.
    • Own the partition-creation job. It is production code with an alert.
    • Think twice about a default partition. It catches stray rows and gets in the way of attach and concurrent detach.
    • Run ANALYZE on the parent. Autovacuum does not.

    Common mistakes

    • Partitioning a table whose queries never use the key.
    • Wrapping the key in a function in the WHERE clause.
    • Expecting a global unique id from a key that must include the partition key.
    • Creating thousands of tiny partitions.
    • Forgetting the next partition, then failing inserts at midnight.
    • Attaching without a matching CHECK, which scans the table under a strong lock.

    Key takeaways

    • One logical table, many physical ones; the parent stores nothing.
    • Range, list and hash differ in what they make cheap: ordered data, named groups, even spread.
    • Pruning needs the bare key in the WHERE; indexes do not drive it.
    • Unique keys must include the partition key.
    • Attach with a matching CHECK; detach concurrently when you cannot hold ACCESS EXCLUSIVE, and not with a default partition.
    • The lab shows plans and lock modes, not waits or timing.

    Practice exercises

    Exercise 1 (20 min). For a list-partitioned table by store region, say what a query for one region and a query for two regions would do, and why a new region needs a new partition.

    Exercise 2 (45 min). Run the lab and explain, from the manual, why query D uses an index in every partition but cannot skip any.

    Exercise 3 (1 hour). Write the monthly job in pseudocode: create ahead, attach with a CHECK, detach concurrently, archive, drop, and the alert.

    Exercise 4 (2 hours). Extend the lab with a list-partitioned table and compare pruning for one value and for two.

    • Sharding: splitting data across servers rather than within one.
    • Hot partitions and resharding: what goes wrong when one slice gets all the traffic.
    • Time-series databases: another home for date-keyed data with retention.
    • Unique ID generation: ids that stay unique without cross-partition constraints.
    • Schema evolution and zero-downtime migrations: the migration pattern for moving a live table (a separate lesson, named in plain text).

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments