Sub topic 6
Choosing a partition key
This chapter assumes you can create a partitioned table with PARTITION BY and PARTITION OF, and that you know the range, list and hash methods. You should also be able to read a basic EXPLAIN plan. The question here is which column or expression to partition on. That choice is hard to undo, because PostgreSQL cannot change the key of an existing partitioned table.
What the key decides
The partition key is the set of columns or expressions that PostgreSQL uses to send each row to one partition. It affects four things:
- Pruning. The planner can skip partitions only when a query's
WHEREclause (or join condition) constrains the key. - Keys and constraints. Every primary key and unique constraint must include all key columns.
- Data lifecycle. Detaching or dropping a partition removes a whole slice of data cheaply, but only if the slices match your retention rule.
- Balance. The key controls how evenly rows and write traffic spread across partitions.
A key can be one column, several columns, or an expression in parentheses. Most real tables use a single column.
Criteria for a good key
1. It appears in the filters of your important queries
Pruning is the main payoff of partitioning. List the queries that matter most, either the slowest or the most frequent. Check which column each one filters on with equality, IN or a range. If most of them filter on recorded_at, that is your candidate. If they filter on many different columns with no common one, partitioning will not speed them up.
The next example shows the cost of a key that queries do not use. Both partitions are created with the bounds from this chapter's pattern.
CREATE TABLE orders (
order_id bigint NOT NULL,
placed_at date NOT NULL,
total numeric,
PRIMARY KEY (order_id, placed_at)
) PARTITION BY RANGE (placed_at);
CREATE TABLE orders_2026_01 PARTITION OF orders
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
CREATE TABLE orders_2026_02 PARTITION OF orders
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');
-- No filter on the key: every partition is scanned.
EXPLAIN SELECT * FROM orders WHERE order_id = 42;
-- Filter on the key: only orders_2026_02 is scanned.
EXPLAIN SELECT * FROM orders WHERE order_id = 42 AND placed_at = '2026-02-03';The first plan lists both partitions, each with its own index scan. The cost grows with the partition count, because PostgreSQL probes one index per partition. The second plan lists one. If lookups by order_id alone dominate your workload, date partitioning makes them slower than an unpartitioned table.
2. It matches the data lifecycle
If you keep 13 months of data and delete the oldest month each month, partition by month. DETACH PARTITION followed by DROP TABLE then replaces a large DELETE and the vacuum work it causes. If your retention rule is "delete a tenant's data when they leave", a key on tenant_id fits better. A key that does not match the rule gives you no cheap deletion. You would still run DELETE statements inside each partition.
3. It spreads rows sensibly
Check the distribution before you commit. A list key on region is poor if one region holds 90% of the rows, because that partition behaves like the original large table. Hash partitioning spreads rows evenly by design, but it gives up two things. It cannot prune on ranges, and it cannot drop old data by detaching.
4. The partition count stays manageable
Planning time and memory use grow with the number of partitions. Dozens to a few hundred partitions is typical. Thousands need testing. Daily partitions over ten years give roughly 3,650 partitions, while monthly partitions over the same period give 120. Pick the granularity that gives partitions large enough to be worth having, which is often millions of rows or more each.
Matching method to key
| Key shape | Method | Pruning works for | Lifecycle fit | Main risk |
|---|---|---|---|---|
| Timestamp or date | Range | `=`, `<`, `>`, `BETWEEN` | Drop oldest slice | Rows outside all ranges, so you need new partitions created ahead of time |
| Small set of categories | List | `=`, `IN` | Drop one category | Skewed sizes, new values with no partition |
| Id with no natural grouping | Hash | `=` and `IN` only | Poor | No range pruning, no cheap deletion |
| Tenant or customer id | List or hash | `=`, `IN` | Depends on the offboarding rule | Many tenants mean many partitions with list |
Pruning on a hash key requires equality, because a range of values maps to all remainders.
Rules the key must follow
Unique constraints include the key
A primary key or unique constraint on a partitioned table must contain every partition key column. PostgreSQL enforces uniqueness inside each partition's own index. It can guarantee global uniqueness only when the key columns are part of the constraint. In the orders example, order_id alone is rejected. (order_id, placed_at) is accepted, and it guarantees uniqueness of the pair, not of order_id by itself.
You can reduce the practical impact by generating order_id from a single sequence, so duplicates do not occur in practice. The database still does not enforce it. Foreign keys that reference orders must then include placed_at too. Count this cost before choosing a key that your schema cannot carry through its relationships.
Expressions need care
An expression key must use only immutable functions, and queries must use the same expression to get pruning. A constraint on the raw column does not prune a table partitioned on an expression.
CREATE TABLE customers_by_region (
customer_id bigint NOT NULL,
region text NOT NULL,
name text
) PARTITION BY LIST (lower(region));
CREATE TABLE customers_by_region_emea PARTITION OF customers_by_region
FOR VALUES IN ('emea');
CREATE TABLE customers_by_region_other PARTITION OF customers_by_region
DEFAULT;
-- Prunes: the filter uses the same expression as the key.
EXPLAIN SELECT * FROM customers_by_region WHERE lower(region) = 'emea';
-- Does not prune: the planner does not connect region to lower(region).
EXPLAIN SELECT * FROM customers_by_region WHERE region = 'emea';Primary keys and unique constraints cannot be created on a table whose key contains an expression. For that reason, simple column keys are usually the better choice. If you need a derived value, store it in a real column and partition on that.
Time zones affect timestamptz bounds
For a timestamptz key, the bound literal '2026-02-01' is converted using the session's TimeZone setting when you run the CREATE TABLE. Two administrators in different time zones create different partition boundaries. State the offset explicitly:
CREATE TABLE readings (
device_id int NOT NULL,
recorded_at timestamptz NOT NULL,
value numeric
) PARTITION BY RANGE (recorded_at);
CREATE TABLE readings_2026_02 PARTITION OF readings
FOR VALUES FROM ('2026-02-01 00:00:00+00') TO ('2026-03-01 00:00:00+00');Then your month boundaries are UTC midnight no matter who runs the script. A query that groups by local-time days still prunes by instant, so a local "February" query may touch two partitions near the edges.
The key value decides placement
If an UPDATE changes a key column, PostgreSQL moves the row to the correct partition. This is supported but costs a delete plus an insert. Pick a key that never changes after insert, such as a creation timestamp, not a status or "last modified" column.
Multiple columns
A range key can have several columns, for example PARTITION BY RANGE (tenant_id, created_at). Bounds compare column by column from the left. Pruning on a later column works only when the earlier ones are also constrained by equality. For that reason, this form is much less common than a single-column key, and a multilevel layout (range by time, then hash by tenant) is usually easier to reason about.
A decision path
Common mistakes
- Choosing a key because it is convenient to partition on, not because queries filter on it.
- Using
created_atfor a table where lookups go by primary key alone. - Using a mutable column such as
statusas the key. - Relying on a session-dependent time zone for
timestamptzbounds. - Creating one partition per day for a small table, which adds planning overhead without benefit.
Exercise
A table events(event_id bigint, tenant_id int, created_at timestamptz, payload jsonb) is queried mostly with WHERE tenant_id = $1 AND created_at >= now() - interval '7 days'. Rows older than 90 days are deleted nightly. Which partition key and method would you choose, and what must the primary key contain?
Show answer
Range on createdat is the best primary key, because it matches the retention rule (drop whole old partitions) and the recent-days filter prunes to a few partitions. The primary key must include createdat, for example (eventid, createdat). If tenant lookups are also heavy, you can subpartition each range by hash on tenant_id, and the key must then include both columns.
Exercise
Why does SELECT * FROM orders WHERE order_id = 42 scan every partition when orders is partitioned by placed_at, and how can you make it prune?
Show answer
The planner can only exclude a partition when the WHERE clause constrains the partition key, and this query constrains only orderid. Add a condition on placedat (for example the known order date or a range), or choose a different partition key if lookups by order_id are the dominant workload.
Exercise
You partition readings on a timestamptz column and write bounds like FROM ('2026-02-01') without an offset. What can go wrong?
Show answer
The literal is converted using the TimeZone setting of the session that runs the statement, so the same script run in different time zones creates different boundaries. Write the offset explicitly, such as '2026-02-01 00:00:00+00'.