Sub topic 5
Partitioning by Explicit Values
Assume you know basic PostgreSQL table definitions, constraints, indexes, and simple query plans. This chapter focuses on list partitioning and hash partitioning. Both use one logical table name, while PostgreSQL stores rows in separate child tables.
Partitioning by explicit values
List partitioning assigns a row to a partition according to a fixed set of values. It fits columns with a small, stable set of categories, such as ticket status, region, or account type.
CREATE TABLE tickets (
ticket_id bigint NOT NULL,
tenant_id integer NOT NULL,
status text NOT NULL
) PARTITION BY LIST (status);
CREATE TABLE tickets_open
PARTITION OF tickets
FOR VALUES IN ('open', 'pending');
CREATE TABLE tickets_closed
PARTITION OF tickets
FOR VALUES IN ('closed');The partition key is status. An insert with status = 'open' goes to tickets_open. An insert with status = 'closed' goes to tickets_closed.
INSERT INTO tickets (ticket_id, tenant_id, status)
VALUES (1, 42, 'open');
SELECT tableoid::regclass AS physical_partition, ticket_id, status
FROM tickets
WHERE ticket_id = 1;tableoid identifies the physical table that contains the row. The query still reads through the parent table, tickets.
A value cannot belong to two list partitions. PostgreSQL rejects overlapping definitions when you create or modify partitions. However, a value that belongs to no partition causes an insert error.
You can define a default partition for values not listed elsewhere:
CREATE TABLE tickets_other
PARTITION OF tickets DEFAULT;When adding a new explicit partition, check the default partition first. PostgreSQL must ensure that its rows do not violate the new partition's bounds.
Partitioning by hash
Hash partitioning computes a hash from the partition key and assigns the result to one of a fixed number of partitions. It is useful when you want to spread rows evenly but have no meaningful ranges or categories.
CREATE TABLE events (
event_id bigint NOT NULL,
payload jsonb NOT NULL
) PARTITION BY HASH (event_id);
CREATE TABLE events_0 PARTITION OF events
FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE events_1 PARTITION OF events
FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE events_2 PARTITION OF events
FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE events_3 PARTITION OF events
FOR VALUES WITH (MODULUS 4, REMAINDER 3);MODULUS 4 divides the hash space into four groups. Each REMAINDER identifies one group. All partitions must use compatible modulus and remainder definitions.
Hash partitioning does not preserve order. A range query on event_id usually cannot eliminate partitions based on the numeric interval. Equality queries on the partition key can often identify the relevant partition.
Exercise
Which partitioning method fits a table whose rows have statuses such as open, pending, and closed?
Show answer
List partitioning, because each status can be assigned explicitly to a partition.