How do I avoid an integer result when dividing aggregate totals?
Quick answer
In SQLite, dividing two integer expressions can use integer division, which truncates toward zero. Make one operand REAL before dividing—for example, 1.0 * SUM(amount) / SUM(quantity)—so the ratio can include a fractional part. Check separately that the denominator is not zero and account for possible NULL values; converting an operand does not settle those cases. [S1]
The question, the details, the next step.
A practical checklist
Confirm that the two aggregate totals have the intended meaning and units.
Convert an operand to REAL before division, such as with
1.0 * SUM(amount).Check whether the denominator can be zero or whether the input can be empty.
Decide how NULL values should affect the result.
Compare a test result with a small hand-calculated example.
A few more useful answers
Does multiplying by 1.0 change the aggregate total?
It makes that operand REAL for the division expression, allowing a fractional result instead of integer division. [S1]
Will the fractional expression handle a zero denominator?
No. SQLite’s documented fractional-expression example does not remove the need to handle an empty or zero denominator separately. [S1]
Is total amount divided by total quantity always the average I need?
Not necessarily. It gives the combined amount per combined quantity; confirm that this is the measure your task requires.
Sources
References used for this guide.
- [S1] SQLite SQL Language Expressions sqlite.org · Checked
