SQL Server
SELECT 7 / 2 AS IntDiv, 7 / 2.0 AS ExactDiv, 7 % 2 AS Remainder;
int / int truncates to 3. Make either operand a decimal (2.0) or CAST it, and you get 3.500000.
The most common silent bug when porting SQL: three engines truncate, two do not.
Filed under Types & casting
Know which side of the divide your engine is on: SQL Server, PostgreSQL and SQLite truncate integer division; MySQL and Oracle never do. Hand-written averages and ratios that divide two integer columns are where this bites.
Whether / truncates depends on the engine and the operand types. SQL Server, PostgreSQL and SQLite truncate integer / integer; MySQL and Oracle always return the exact quotient. Each row shows both the trap and the fix.
SELECT 7 / 2 AS IntDiv, 7 / 2.0 AS ExactDiv, 7 % 2 AS Remainder;
int / int truncates to 3. Make either operand a decimal (2.0) or CAST it, and you get 3.500000.
SELECT 7 / 2 AS IntDiv, 7 / 2.0 AS ExactDiv, 7 % 2 AS Remainder;
Same rule: integer operands truncate, and a NUMERIC literal promotes the expression to 3.5000000000000000. div(7, 2) is the explicit integer-division function.
SELECT 7 DIV 2 AS IntDiv, 7 / 2 AS ExactDiv, 7 % 2 AS Remainder;
Inverted convention: / is always exact (3.5000) and DIV is the explicit integer division. MOD is a reserved word, so it cannot be an unquoted alias.
SELECT 7 / 2 AS IntDiv, 7 / 2.0 AS ExactDiv, 7 % 2 AS Remainder;
int / int truncates to 3; a REAL operand promotes. Watch out for SUM()/COUNT() patterns on integer columns.
SELECT 7 / 2 AS ExactDiv, MOD(7, 2) AS Remainder FROM dual;
Always exact NUMBER division (3.5); there is no integer-division operator, so TRUNC(7/2) when you want 3.
Because both operands are integers in the truncating engines. Cast one side: SUM(a) * 1.0 / COUNT(*), or CAST(SUM(a) AS DECIMAL) / COUNT(*).
Not as a single operator: DIV exists only in MySQL, and PostgreSQL has div(a, b). FLOOR(a * 1.0 / b) differs from truncation for negatives (FLOOR(-3.5) is -4, truncation gives -3), so decide which semantics you want for negative operands.
share * 100 / total on integer columns truncates every share to 0. Multiply by 100.0 first, or cast before dividing.
Text '42' becomes 42 everywhere, but 'abc' raises an error in three engines and quietly becomes 0 in two.
Five engines, four different formatting idioms for the same 1,234,567.89.
CAST runs on all five engines; the native forms add format masks, style codes or a shorter spelling.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.