Modulo Sign Follows The Dividend
PostgreSQL % and mod() return a remainder carrying the dividend sign, so negative ids hash to negative buckets unless you wrap with mod(mod(x,n)+n,n).
Code
-- PostgreSQL:% 与 mod() 都是"符号跟随被除数"(截断除法的余数)
SELECT
7 % 3 AS seven_mod_three, -- 1
-7 % 3 AS neg_dividend, -- -1:不是 2
7 % -3 AS neg_divisor, -- 1
mod(-7, 3) AS mod_function; -- -1,与 % 完全一致
-- 想要数学取模(结果总在 [0, 除数)):先 mod,再加除数,再 mod 一次
SELECT
-7 % 3 AS truncated, -- -1
mod(mod(-7, 3) + 3, 3) AS mathematical; -- 2
-- 分桶场景的坑:负 id 直接得到负桶号,映射到不存在的分片
WITH keys(k) AS (VALUES (-1), (0), (1), (4))
SELECT
k,
k % 3 AS raw_bucket, -- -1 会拿到 -1
mod(mod(k, 3) + 3, 3) AS safe_bucket -- 恒为 0..2
FROM keys
ORDER BY k;The sequence inside the code
SELECT statements share the script, touching keys.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; an ORDER BY that fixes the output order.
Applying it
Point it at the keys table.
Statements that matter
WITH keys(k) AS (VALUES (-1), (0), (1), (4))
SELECT
k,
k % 3 AS raw_bucket, -- -1 会拿到 -1
mod(mod(k, 3) + 3, 3) AS safe_bucket -- 恒为 0..2
FROM keys
ORDER BY k;
SELECT
7 % 3 AS seven_mod_three, -- 1
-7 % 3 AS neg_dividend, -- -1:不是 2
7 % -3 AS neg_divisor, -- 1
mod(-7, 3) AS mod_function; -- -1,与 % 完全一致
SELECT
-7 % 3 AS truncated, -- -1
mod(mod(-7, 3) + 3, 3) AS mathematical; -- 2
Interactive Tools for This Topic
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.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.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- `keys`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.