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.
Code
-- 哈希分区按分区键的哈希取模路由,不依赖业务列的天然范围
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
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
FAQ
- What relations does the SQL touch?
- `events` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.