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).

SqlData Integrity

Code

snippet
-- 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

FAQ

Which tables appear in this script?
`keys`.