← Back to SQL, page 25

sql-0482 · Easy fresher

Predict SELECT 10 / 3 * 3, 10 * 3 / 3 in SQLite.

The results are 9 and 10. Both operators have the same precedence and are evaluated left to right; in the first expression 10 / 3 truncates to 3 before multiplying, while the second multiplies first and divides 30 by 3 exactly.

Full answer
sql
SELECT 10 / 3 * 3 AS divide_first, 10 * 3 / 3 AS multiply_first, 10.0 / 3 * 3 AS real_math;
divide_firstmultiply_firstreal_math
91010.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