SQL Integer Division: Percentages Come Out 0
In many SQL engines, dividing two integers can truncate the fraction. Multiply by 100.0 and round.
The symptom
You compute a rate like shipped / total and every value comes
back 0 or a whole number in some databases, even though the
real answer is a fraction like 0.708.
Why it happens
In engines such as Postgres and SQL Server, dividing one integer by another
does integer division, which throws away the remainder.
17 / 24 becomes 0, not 0.708.
The fix
Force the math to be fractional by making one side a decimal. The cleanest
trick is to start a percentage with 100.0. Then
round() for a tidy result.
select shipped / total as rate -- can truncate to 0 select round(100.0 * shipped / total, 1) as pct
-- 100.0 is a decimal-friendly, portable habit
DuckDB (which powers SQLShed) actually does fractional division with
/ by default, so 17 / 24 is 0.708
here. The 100.0 habit costs nothing and keeps your query
portable to engines where integer division truncates.
Learn more
Related
Turn rows into counts.
COUNT, SUM, AVG, MIN, MAX, GROUP BY, and HAVING.
COUNT, SUM, AVG, GROUP BY, and HAVING.
Practice aggregate reports, HAVING, and answer shape.
Group or aggregate every selected column.
Calculate totals, averages, and extremes.