Integer Division Truncates Toward Zero

Dividing two integers keeps the result an integer and truncates toward zero: -7 / 2 yields -3, and only a numeric cast restores the fraction.

SqlData Integrity

Code

snippet
-- 两个 integer 相除仍是 integer:结果向零截断 (truncates toward zero),不是 floor
-- 日常 bug:平均数、比例、分页总数都会被悄悄砍掉小数
SELECT
    7  / 2   AS seven_over_two,     -- 3
    -7 / 2   AS neg_seven_over_two, -- -3:朝零截断,floor 才是 -4
    9  / 4   AS quotient,           -- 2
    9  % 4   AS remainder,          -- 1
    -7 % 2   AS neg_remainder;      -- -1:余数符号跟随被除数

-- 想要真实除法:任一侧换成 numeric
SELECT
    7::numeric / 2 AS exact_division,   -- 3.5
    7 / 2.0        AS promoted,         -- 3.5:字面量带小数点即 numeric
    round(7::numeric / 2, 1) AS rounded_one_dp;  -- 3.5
-- AVG(int_col) 本身返回 numeric:聚合函数内部已按 numeric 计算

Integer Division Truncates Toward Zero, line by line

SELECT statements share the script.

Neither statement reads a table — every operand is a literal, so the division semantics are observable without any schema. The first statement keeps every operand an integer, which is why seven_over_two prints 3 and neg_seven_over_two prints -3: the quotient is truncated toward zero rather than floored. The second statement promotes one side to numeric with 7::numeric / 2, and the same pair of values then yields 3.5 — the cast, not the division itself, decides whether the fraction survives.

The remainder operator follows the same sign rule: 9 % 4 prints 1 and neg_remainder prints -1, taking its sign from the dividend. When you need both a real quotient and a remainder, compute them in numeric first and cast once at the end, instead of trying to reassemble them from truncated integer parts.

Statements that matter

SELECT
    7  / 2   AS seven_over_two,     -- 3
    -7 / 2   AS neg_seven_over_two, -- -3:朝零截断,floor 才是 -4
    9  / 4   AS quotient,           -- 2
    9  % 4   AS remainder,          -- 1
    -7 % 2   AS neg_remainder;      -- -1:余数符号跟随被除数
SELECT
    7::numeric / 2 AS exact_division,   -- 3.5
    7 / 2.0        AS promoted,         -- 3.5:字面量带小数点即 numeric
    round(7::numeric / 2, 1) AS rounded_one_dp;  -- 3.5

Interactive Tools for This Topic