Sub topic 4
List partitioning by discrete values
Prerequisites
This chapter assumes you can write CREATE TABLE, INSERT and SELECT, and that you know what a primary key is. You should also know that a partitioned table is a parent with no storage of its own, and that its rows live in child partitions. Range partitioning was covered in an earlier chapter, so the focus here is on what is different about lists.
What list partitioning does
List partitioning assigns each row to a partition by comparing the row's partition key value with an explicit list of values. Each partition declares the values it owns. A row goes to the partition whose list contains its key. Rows are never placed by order or by arithmetic.
List partitioning fits columns that hold a small, known set of discrete values. Typical examples are region, country, tenant tier, status, or product line. If the values are open-ended or ordered, such as timestamps, range partitioning is usually the better match.
Creating a list partitioned table
The parent table is declared with PARTITION BY LIST. Each partition is created with PARTITION OF ... FOR VALUES IN (...).
CREATE TABLE customers (
customer_id bigint NOT NULL,
region text NOT NULL,
name text,
PRIMARY KEY (customer_id, region)
) PARTITION BY LIST (region);
CREATE TABLE customers_emea PARTITION OF customers FOR VALUES IN ('emea');
CREATE TABLE customers_amer PARTITION OF customers FOR VALUES IN ('amer', 'latam');Three details in this example matter.
- The partition key is
region. A list partitioned table can have only one key column. Range partitioning allows several columns, but list partitioning does not. customers_amerowns two values,'amer'and'latam'. A partition can hold any number of values, and this is how you group related values into one physical table.- The primary key is
(customer_id, region). It includes the partition key because PostgreSQL requires that. The reason is covered below.
How rows are routed
When you insert into the parent, PostgreSQL evaluates the key and finds the matching partition. You can see the result with tableoid::regclass, which reports the partition that stores each row.
INSERT INTO customers (customer_id, region, name) VALUES
(1, 'emea', 'Anna'),
(2, 'amer', 'Bob'),
(3, 'latam', 'Carla');
SELECT tableoid::regclass AS partition, customer_id, region
FROM customers
ORDER BY customer_id;Customer 1 lands in customers_emea. Customers 2 and 3 both land in customers_amer, because that partition lists both values.
Matching is by equality on the key's data type and collation rules. For a text key, 'EMEA' does not match 'emea'. A row with the value 'EMEA' would find no partition, and the insert would fail unless a default partition exists.
INSERT INTO customers (customer_id, region, name) VALUES (4, 'apac', 'Dan');This fails with an error saying that no partition of relation "customers" was found for the row. The next section covers how to deal with this.
Rows with no matching partition
Unlike range partitioning, where a gap between ranges is easy to see, a list partition set is only complete if you have listed every value that can occur. A new value such as 'apac' has no home. You have two options.
- Add a partition for the new value before data arrives.
- Create a default partition that receives every row that matches no other partition.
CREATE TABLE customers_default PARTITION OF customers DEFAULT;A default partition prevents insert errors, but it has costs.
- Rows pile up there silently. A typo such as
'emae'is accepted and stored in the default partition, where it may go unnoticed. - Adding a new partition for a value later requires PostgreSQL to scan the default partition. It must confirm that no existing row there belongs to the new partition. On a large default partition this scan is slow and takes a lock.
- If the default partition already contains rows with the value you want to add, the
CREATE TABLE ... PARTITION OFcommand fails. You must move those rows out first.
A common practice is to keep a default partition as a safety net, monitor its row count, and treat any rows in it as a data quality problem to resolve.
SELECT count(*) FROM customers_default;NULL values
A NULL key needs a partition too. For list partitioning, you can include NULL in a partition's list.
CREATE TABLE tickets (
ticket_id bigint NOT NULL,
status text,
PRIMARY KEY (ticket_id)
) PARTITION BY LIST (status);This example would fail, because the primary key does not include status. The following version is valid, and it routes NULL explicitly.
CREATE TABLE tickets (
ticket_id bigint NOT NULL,
status text,
PRIMARY KEY (ticket_id, status)
) PARTITION BY LIST (status);That also fails, because primary key columns are implicitly NOT NULL, so status cannot be NULL. This is a useful lesson. When a key column must allow NULL, you cannot make it part of a primary key, so choose either NOT NULL on the key or a unique index design that fits. For a nullable list key without a primary key, route nulls like this:
CREATE TABLE tickets (
ticket_id bigint NOT NULL,
status text
) PARTITION BY LIST (status);
CREATE TABLE tickets_open PARTITION OF tickets FOR VALUES IN ('open', 'reopened');
CREATE TABLE tickets_closed PARTITION OF tickets FOR VALUES IN ('closed');
CREATE TABLE tickets_none PARTITION OF tickets FOR VALUES IN (NULL);Only one partition may list NULL. Without such a partition or a default partition, inserting a NULL key fails.
Partition bounds must not overlap
Each value can appear in only one partition. PostgreSQL rejects a partition whose list overlaps an existing one.
CREATE TABLE customers_overlap PARTITION OF customers FOR VALUES IN ('emea', 'mea');This fails because 'emea' already belongs to customers_emea. The check applies at creation and attach time, so the partition set is always unambiguous.
Pruning with lists
Partition pruning lets the planner skip partitions that cannot contain matching rows. For list partitioning, pruning works when the query compares the key with constants or parameters.
EXPLAIN
SELECT * FROM customers WHERE region = 'emea';The plan should scan only customers_emea. Other partitions are absent from the plan. The same holds for region IN ('amer', 'latam'), which selects only customers_amer, and for region = 'amer', which also selects only customers_amer (the partition is chosen because it contains the value, even though it contains others).
Pruning does not occur when the filter does not reference the key. A query filtering on name alone scans every partition. Wrapping the key in an expression can also defeat pruning, for example WHERE lower(region) = 'emea', because the planner cannot relate the expression to the stored lists.
| Filter | Partitions scanned |
|---|---|
| `region = 'emea'` | `customers_emea` |
| `region IN ('amer', 'emea')` | `customers_amer`, `customers_emea` |
| `region <> 'emea'` | every other partition, including the default one |
| `lower(region) = 'emea'` | all partitions |
| `name = 'Anna'` | all partitions |
Why primary keys must include the key
PostgreSQL enforces unique constraints inside each partition's own index. It has no global index that spans partitions. A uniqueness rule is therefore only safe if two equal values can never end up in different partitions. That holds only when the constraint includes the partition key, since equal keys always route to the same partition.
In the customers example, customer_id alone could repeat across emea and amer, and no partition would notice. The primary key (customer_id, region) guarantees uniqueness of the pair. If you need customer_id to be unique by itself, list partitioning on region cannot enforce it. Consider another key, or enforce uniqueness in the application or through a separate lookup table.
Choosing between list and its neighbours
| Situation | Method |
|---|---|
| A small set of named values, such as regions or tiers | List |
| Ordered data such as dates or ids | Range |
| No natural grouping and an even spread is wanted | Hash |
Lists also suit data that is purged or moved by group. Dropping all rows for one region becomes DROP TABLE customers_emea after a detach, rather than a large DELETE.
Common pitfalls
- Skewed sizes. If one region holds 90 percent of the rows, that partition is nearly as large as the original table, and partitioning gains little.
- Growing value sets. If new values appear often, such as one per customer, the number of partitions grows. Very large partition counts raise planning time and memory use.
- Unlisted values with no default partition cause insert failures in production. Decide ahead of time how new values are introduced.
- Case and whitespace differences create separate values. Consider a
CHECKconstraint or an enum type to keep keys clean.
Exercise
A table shipments is partitioned BY LIST (carrier). A partition shipments_dhl is declared FOR VALUES IN ('dhl'). A default partition exists and already holds 200 rows with carrier 'ups'. You now run CREATE TABLE shipments_ups PARTITION OF shipments FOR VALUES IN ('ups');. What happens, and how do you fix it?
Show answer
The command fails, because the default partition holds rows that belong to the new partition and PostgreSQL will not let them stay there. To fix it, move the rows out first. For example, create shipments_ups as a standalone table, copy the 'ups' rows into it, delete them from the default partition, and then attach it with ALTER TABLE shipments ATTACH PARTITION shipments_ups FOR VALUES IN ('ups');. Do the copy and delete in one transaction so no rows are lost or duplicated.
Exercise
Why does PRIMARY KEY (customer_id) fail on customers when it is partitioned by LIST (region), and what is the smallest change that makes it valid?
Show answer
PostgreSQL has no index that spans partitions, so a unique constraint must include the partition key to guarantee that equal values land in the same partition. Changing the key to PRIMARY KEY (customer_id, region) makes it valid.