Sub topic 5
Hash partitioning with modulus and remainder
This chapter assumes you can write CREATE TABLE and CREATE INDEX, read basic EXPLAIN output, and know that a primary key is a unique, non-null constraint. It also assumes you have seen PARTITION BY and PARTITION OF in the earlier chapters on range and list partitioning.
When hash partitioning fits
Range partitioning needs a natural ordering such as time. List partitioning needs a small set of known values. Many tables have neither. An accounts table keyed by account_id has no date to cut on and no short list of categories. Hash partitioning handles this case by spreading rows evenly across a fixed number of partitions.
Typical reasons to use it:
- Splitting a large table so that vacuum, index builds and index sizes are manageable per partition.
- Spreading write load and cache pressure across several smaller B-tree indexes.
- Enabling partitionwise joins between two tables that are hash partitioned the same way (covered in a later chapter).
Hash partitioning gives you no data lifecycle benefit. You cannot drop "the old rows" by dropping a partition, because old and new rows are mixed in every partition. If retention drives your design, use range partitioning.
How a row finds its partition
You declare the strategy on the parent table and then create one partition for each remainder.
CREATE TABLE accounts (
account_id bigint NOT NULL PRIMARY KEY,
owner text
) PARTITION BY HASH (account_id);
CREATE TABLE accounts_p0 PARTITION OF accounts FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE accounts_p1 PARTITION OF accounts FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE accounts_p2 PARTITION OF accounts FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE accounts_p3 PARTITION OF accounts FOR VALUES WITH (MODULUS 4, REMAINDER 3);On each insert, PostgreSQL does the following:
- It computes a hash value from the partition key column or columns, using the hash function of the column's data type.
- It divides that hash value by the modulus and takes the remainder.
- It stores the row in the partition whose declared remainder matches.
The hash function is deterministic, so the same key always goes to the same partition. You cannot predict a partition by reading the key, though. The hash is not the key's value modulo 4. Do not assume that account_id = 5 lands in accounts_p1.
Notice that the primary key on account_id is allowed here. A unique constraint on a partitioned table must include all partition key columns, and account_id is the whole key.
Checking the distribution
Load some rows and count them per partition. tableoid::regclass shows which partition stores each row.
INSERT INTO accounts (account_id, owner)
SELECT g, 'owner_' || g
FROM generate_series(1, 100000) AS g;
SELECT tableoid::regclass AS partition, count(*)
FROM accounts
GROUP BY 1
ORDER BY 1;With sequential integer keys, each of the four partitions should hold roughly 25,000 rows. The counts will not be identical. Hashing gives an even spread on average, not a perfect one. Heavy skew usually means the key has few distinct values (see the pitfalls below).
The rules for moduli and remainders
Each partition declares a pair (MODULUS m, REMAINDER r), with 0 <= r < m. PostgreSQL enforces these rules:
- Two partitions of the same parent cannot claim the same hash values. Two partitions both declared
MODULUS 4, REMAINDER 0conflict. - You may mix moduli, but every modulus must be a factor of the next larger one. A parent can combine moduli 2, 4 and 8. It cannot combine 3 and 4, because 3 is not a factor of 4.
- Every hash value must have a home when you insert. If you create only some of the remainders, a row that hashes to a missing remainder fails.
The second rule is what makes growth possible. A partition with modulus 4 and remainder 0 holds exactly the hash values that a pair of modulus 8 partitions, with remainders 0 and 4, would hold between them. So you can split one partition into two without touching the others.
A parent can be left incomplete. A hash partitioned table cannot have a default partition, so there is no catch-all for missing remainders. The error looks like this:
CREATE TABLE sparse (id int NOT NULL) PARTITION BY HASH (id);
CREATE TABLE sparse_p0 PARTITION OF sparse FOR VALUES WITH (MODULUS 2, REMAINDER 0);
-- Succeeds or fails depending on where the hash of each id falls.
INSERT INTO sparse SELECT generate_series(1, 10);
-- ERROR: no partition of relation "sparse" found for rowPruning works for equality only
Partition pruning on hash partitions depends on the query comparing the key for equality. PostgreSQL can compute the hash of a constant, find the one matching remainder, and skip the others.
EXPLAIN SELECT * FROM accounts WHERE account_id = 42;The plan should show a scan of one partition only. Which partition appears depends on the hash of 42. IN (...) lists also prune, down to the partitions that the listed values hash into.
Range conditions do not prune:
EXPLAIN SELECT * FROM accounts WHERE account_id BETWEEN 100 AND 200;Adjacent keys hash to unrelated partitions, so this plan scans every partition. If most of your queries filter on ranges of the key, hash partitioning on that key gives you more overhead and no benefit.
A query that does not filter on the partition key at all also scans every partition. Each partition adds planning work and a separate index probe, so a lookup by some other column becomes four index lookups instead of one.
Multiple columns and other types
The partition key can list more than one column, and the hash combines them:
CREATE TABLE tenant_docs (
tenant_id int NOT NULL,
doc_id bigint NOT NULL,
body text,
PRIMARY KEY (tenant_id, doc_id)
) PARTITION BY HASH (tenant_id, doc_id);Pruning then needs equality conditions on all key columns. Filtering on tenant_id alone cannot determine the hash and scans every partition. A single-column key is usually the better choice unless the queries always supply both values.
Some practical notes on types:
- A row with a NULL in the key is still routed. PostgreSQL treats the hash of NULL as a fixed value, so such rows all go to the same partition.
- Text keys must use a deterministic collation. The hash of a string depends on its bytes.
- A hash partition can itself be partitioned. A later chapter shows hash partitions nested below range partitions.
Growing from four to eight partitions
Suppose the four partitions have become too large. You can split accounts_p0 into two modulus 8 partitions and leave the other three alone. The result is valid because 4 is a factor of 8.
BEGIN;
ALTER TABLE accounts DETACH PARTITION accounts_p0;
ALTER TABLE accounts_p0 RENAME TO accounts_p0_old;
CREATE TABLE accounts_m8_r0 PARTITION OF accounts FOR VALUES WITH (MODULUS 8, REMAINDER 0);
CREATE TABLE accounts_m8_r4 PARTITION OF accounts FOR VALUES WITH (MODULUS 8, REMAINDER 4);
INSERT INTO accounts SELECT * FROM accounts_p0_old;
DROP TABLE accounts_p0_old;
COMMIT;The steps in order:
- Detach the old partition. Its rows are no longer visible through
accounts. - Create the two replacement partitions. The new partitions inherit the primary key from the parent.
- Reinsert the rows through the parent. PostgreSQL routes each row to the new partition that matches its hash, and also checks the primary key.
- Drop the old table.
Doing this in one transaction keeps readers from seeing the table with a gap, but the plain DETACH PARTITION takes an ACCESS EXCLUSIVE lock on the parent. The parent is blocked for reads and writes until commit, and the copy time is part of that. For a big partition, plan a maintenance window, or copy the data into the new tables outside the lock first and attach them afterwards.
Limitations and pitfalls
| Pitfall | Why it happens | What to do |
|---|---|---|
| Skewed partitions | The key has few distinct values, or a few values are far more common than the rest | Choose a high-cardinality key, such as a surrogate id |
| Full scans on range filters | Neighboring keys hash to different partitions | Use range partitioning if range filters dominate |
| Too few partitions chosen | Changing the modulus later means copying rows | Pick a power of two that leaves room, such as 8 or 16 |
| Restoring on a different server encoding | Hash values of text keys can depend on the encoding, so rows can restore into a different partition than they were dumped from | Dump with `pg_dump --load-via-partition-root` |
| Missing remainders | No default partition exists for hash tables | Create every remainder before writes begin |
Summary
Hash partitioning assigns each row to a partition by the remainder of a hash of the key. You declare it with PARTITION BY HASH and one FOR VALUES WITH (MODULUS m, REMAINDER r) clause per partition. It distributes data and write load evenly, and it prunes only for equality on the full key. Moduli must divide each other, which allows growth by splitting a partition. All remainders must exist, because a hash table has no default partition.
Exercise
A table sessions is partitioned BY HASH (session_id) with partitions MODULUS 4, REMAINDER 0, REMAINDER 1 and REMAINDER 2, and no partition for remainder 3. (a) What happens when you insert a row whose key hashes to remainder 3? (b) Can you add a default partition to fix it? (c) Can you create a fourth partition with MODULUS 8, REMAINDER 3 to cover the gap?
Show answer
(a) The insert fails with the error "no partition of relation found for row". (b) No. Hash partitioned tables do not support a default partition. (c) No. A modulus 8 partition covers only the hash values that equal 3 modulo 8, so it would cover part of remainder 3 modulo 4 and also needs remainder 7 to fill it. The fix is to create the missing partition MODULUS 4, REMAINDER 3, or MODULUS 8, REMAINDER 3 together with MODULUS 8, REMAINDER 7, which is allowed because 4 is a factor of 8.