// dialect comparison

Integer and decimal division in SQL Server, PostgreSQL, MySQL, SQLite and Oracle

The most common silent bug when porting SQL: three engines truncate, two do not.

Filed under Types & casting

The verdict

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.

Where they differ

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.

How each engine writes it

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.

PostgreSQL

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.

MySQL

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.

SQLite

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.

Oracle

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.

Questions that come up

Why does SUM(a)/COUNT(*) return an integer?

Because both operands are integers in the truncating engines. Cast one side: SUM(a) * 1.0 / COUNT(*), or CAST(SUM(a) AS DECIMAL) / COUNT(*).

Is there a portable integer division?

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.

How do percentages usually go wrong?

share * 100 / total on integer columns truncates every share to 0. Multiply by 100.0 first, or cast before dividing.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.