Full answer
sql
SELECT 10 / 3 * 3 AS divide_first, 10 * 3 / 3 AS multiply_first, 10.0 / 3 * 3 AS real_math;| divide_first | multiply_first | real_math |
|---|---|---|
| 9 | 10 | 10.0 |
Integer division discards the remainder at the step where it happens, so the position of the division decides how much is lost. With a real operand, as in the third column, the arithmetic is floating point and returns 10.0. PostgreSQL behaves the same for integers. In financial calculations, multiply before dividing, or use NUMERIC or real operands, and round once at the end.
sql
SELECT 10 / 3 * 3 AS divide_first, 10 * 3 / 3 AS multiply_first, 10.0 / 3 * 3 AS real_math;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- * and / evaluate left to right
- Integer division truncates at each step
- Multiply before dividing to keep precision
Common mistakes
- Assuming the two expressions are equal
Follow-ups
- What does 10 % 3 * 3 return?
- How would you compute a percentage safely?
Tips
- Evaluate step by step