Hash Partitioning Modulus Remainder Spread

Hash partitions route rows by modulus and remainder over the partition key, with equality predicates pruning the scan to a single partition.

SqlData Integrity

Code

snippet
-- 哈希分区按分区键的哈希取模路由,不依赖业务列的天然范围
CREATE TABLE events (
    event_id    bigserial,
    customer_id bigint NOT NULL,
    payload     text
) PARTITION BY HASH (customer_id);

-- 同一 modulus 下 remainder 不得重复;覆盖 0..modulus-1 才接得住所有行
CREATE TABLE events_h0 PARTITION OF events FOR VALUES WITH (MODULUS 3, REMAINDER 0);
CREATE TABLE events_h1 PARTITION OF events FOR VALUES WITH (MODULUS 3, REMAINDER 1);
CREATE TABLE events_h2 PARTITION OF events FOR VALUES WITH (MODULUS 3, REMAINDER 2);

INSERT INTO events (customer_id, payload) VALUES (42, 'login'), (7, 'view'), (42, 'logout');

-- 等值谓词命中分区键:计划器把扫描裁剪到单个分区
EXPLAIN
SELECT payload FROM events WHERE customer_id = 42;

-- 条件不落在分区键上:裁剪失效,全部分区都要扫
EXPLAIN
SELECT payload FROM events WHERE payload LIKE 'log%';

What the code does

Several statements share this file — SELECT / INSERT / CREATE / EXPLAIN, with events among the objects involved.

Concretely, the SQL combines: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns.

Applying it

Run the statement against the events table.

Statements that matter

CREATE TABLE events_h0 PARTITION OF events FOR VALUES WITH (MODULUS 3, REMAINDER 0);
CREATE TABLE events_h1 PARTITION OF events FOR VALUES WITH (MODULUS 3, REMAINDER 1);
CREATE TABLE events_h2 PARTITION OF events FOR VALUES WITH (MODULUS 3, REMAINDER 2);

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`events` — referenced directly, no join needed.