Sub topic 1
Why and when to partition a table
Partitioning splits one logical table into several physical tables. Applications keep querying a single name, and PostgreSQL decides which physical pieces to read or write. This chapter explains what partitioning gives you, what it costs, and how to decide whether a given table should be partitioned. The later chapters cover the syntax in detail.
Prerequisites
This chapter assumes you can:
- Write
CREATE TABLE,INSERT, andSELECTstatements and create indexes. - Read basic
EXPLAINoutput, such as scan types and row estimates. - Explain what a primary key and a unique constraint guarantee.
You do not need any earlier experience with partitioning. The examples target PostgreSQL 14 or later.
What partitioning is
Declarative partitioning has existed since PostgreSQL 10. You declare a parent table with a PARTITION BY clause, then create child tables called partitions. Each partition holds the rows that fall in one slice of the data, such as one month, one region, or one hash bucket.
The parent table stores no rows itself. It is a routing layer:
- An
INSERTinto the parent sends each row to the partition whose bounds match. - A
SELECTfrom the parent reads the partitions that could contain matching rows. - Each partition is an ordinary table with its own files, indexes, and storage settings.
What partitioning can give you
Partitioning helps in a few specific ways. Each one depends on how your data and queries are shaped.
Smaller scans through partition pruning
If a query filters on the partition key, the planner can leave out partitions that cannot match. A query for one week of data in a table partitioned by month reads one partition instead of the whole table. This is called partition pruning, and a later chapter shows how to confirm it in EXPLAIN.
Pruning only happens when the filter uses the partition key. A query that filters on any other column must visit every partition.
Cheap removal of old data
Deleting a month of rows from a large table with DELETE is expensive:
- It writes a dead row version for every deleted row.
- It generates write-ahead log (WAL) volume.
- It leaves bloat that
VACUUMmust clean up later.
With partitions, you detach and drop the whole partition for that month. This is a metadata operation plus a file removal, and it takes the same short time whether the partition holds a thousand rows or a billion. For time-based retention, this is the most common reason teams adopt partitioning.
Smaller units of maintenance
Each partition has its own indexes and its own vacuum and analyze state. Autovacuum works on one partition at a time, so a vacuum run touches less data. REINDEX of a single partition is quicker than rebuilding one enormous index. In a time-series table, old partitions stop receiving writes, so they need little vacuum work after their data settles.
Better use of memory and storage
Indexes on a partition are smaller than one index on the whole table. If queries mostly touch recent data, the recent partitions' indexes can stay in cache while old ones stay on disk. You can also move old partitions to a cheaper tablespace, which is a storage location you choose for a table.
Bulk loading
You can load data into a standalone table, add a matching CHECK constraint, and then attach it as a partition. This avoids inserting through the parent. A later chapter covers ATTACH PARTITION.
What partitioning costs
Partitioning adds complexity, and it can slow things down when applied to the wrong table.
| Cost | What happens |
|---|---|
| Planning time | The planner considers every partition, and pruning also takes work. Thousands of partitions can make planning noticeably slower. |
| Queries without the key | A query that does not filter on the partition key scans every partition and may be slower than on one table. |
| Key restrictions | A primary key or unique constraint must include all partition key columns. You cannot enforce uniqueness of `order_id` alone across partitions. |
| Operational work | Someone must create future partitions and drop old ones. A missing partition causes insert errors or sends rows to a default partition. |
| Locking | Operations on a partitioned table lock the parent and the partitions the query touches. Queries that touch many partitions hold many locks. |
The key restriction is the one that most often surprises teams. It follows from the design: PostgreSQL enforces a unique constraint with a separate index inside each partition. It has no single global index, so a constraint can only be guaranteed unique if the partition key is part of it. The chapter on primary keys and unique constraints covers the details.
When to partition
A rule of thumb from the PostgreSQL documentation is that a table starts to benefit when its size exceeds the physical memory of the database server. The exact threshold depends on the application. A 50 GB table on a server with 256 GB of RAM may need no partitioning, while a 50 GB table on a small instance with slow storage may benefit.
Partitioning is a good fit when most of these are true:
- The table is large and keeps growing, typically an append-heavy log, event, or measurement table.
- Most queries filter on one column, such as a timestamp or tenant, that can serve as the partition key.
- Data has a lifecycle: you keep it for a fixed period and then delete or archive it.
- Maintenance such as vacuum, index builds, or deletes on the whole table is becoming too slow.
Partitioning is a poor fit when:
- The table is small or fits comfortably in memory.
- Queries filter on many unrelated columns, so no single key lets the planner prune.
- You need global uniqueness on a column that is not part of any sensible partition key.
- You cannot commit to creating and removing partitions on a schedule.
Check the table first
Before partitioning, measure. This query lists the largest ordinary tables in the public schema, including their indexes and TOAST data (storage for large values):
SELECT relname,
pg_size_pretty(pg_total_relation_size(oid)) AS total_size,
reltuples::bigint AS approx_rows
FROM pg_class
WHERE relkind = 'r'
AND relnamespace = 'public'::regnamespace
ORDER BY pg_total_relation_size(oid) DESC
LIMIT 10;Compare the largest sizes with your server's memory. Then look at your slowest queries and ask whether they filter on a common column.
Alternatives to try first
Partitioning is not the first tool to reach for. Consider these before you commit:
- Better indexes. A composite index or a partial index (an index with a
WHEREclause) often fixes a slow query on a large table. - BRIN indexes. A block range index is tiny and works well on append-only data that is naturally ordered, such as timestamps.
- Autovacuum tuning. Per-table settings can fix bloat problems without changing the table structure.
- Archiving. Moving old rows into a separate table on a schedule solves some retention needs, though you lose the instant drop that partitions give you.
If one of these solves the problem, you keep a simpler schema.
A minimal example
This is the smallest partitioned table, shown only to make the idea concrete. Later chapters explain each clause.
CREATE TABLE measurements (
device_id int NOT NULL,
recorded_at timestamptz NOT NULL,
reading numeric
) PARTITION BY RANGE (recorded_at);
CREATE TABLE measurements_2026_01 PARTITION OF measurements
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
CREATE TABLE measurements_2026_02 PARTITION OF measurements
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');
INSERT INTO measurements VALUES (1, '2026-01-15 10:00+00', 21.4);
SELECT tableoid::regclass AS partition, count(*)
FROM measurements
GROUP BY 1;The SELECT reports measurements_2026_01 as the partition holding the row. Applications never name the partition. They insert into and query measurements.
Retiring January later takes two statements instead of a large DELETE:
ALTER TABLE measurements DETACH PARTITION measurements_2026_01;
DROP TABLE measurements_2026_01;Common mistakes when deciding
- Partitioning a small table. The overhead of planning and operations outweighs any benefit.
- Choosing a key that queries do not use. Every query then scans every partition, and you pay the costs with none of the pruning benefit.
- Creating too many partitions. Daily partitions for ten years means over 3,600 partitions. Pick a granularity that keeps the count in the hundreds at most unless you have tested larger numbers.
- Expecting partitioning to speed up every query. It speeds up queries that prune. It slows down some others.
- Forgetting that someone must create the next partition. Plan automation before the first insert fails.
Exercise
A 2 GB table on a server with 64 GB of RAM is slow for queries that filter on customeremail. The team proposes partitioning it by createdat. Give two reasons this is likely the wrong fix, and name one thing to try first.
Show answer
The table is small relative to memory, so it is unlikely to benefit from partitioning. The slow queries also filter on customeremail, not createdat, so the planner could not prune partitions and would scan all of them. Try a B-tree index on customer_email first.
Exercise
A table stores application events and the business keeps 12 months of history, deleting older data every month with a DELETE statement that takes hours and causes bloat. Which partitioning method and key suit this table, and how does partitioning change the monthly deletion?
Show answer
Range partitioning on the event timestamp, with one partition per month. Instead of a bulk DELETE, you detach the oldest partition and drop it, which removes the data without dead rows, heavy WAL volume, or vacuum work.