A query divides two integer columns as 7 / 2. What is returned, and how is a decimal result obtained?
Correct answer
B. 3, because integer division truncates; cast one operand to numeric to get 3.5
16 views
B. 3, because integer division truncates; cast one operand to numeric to get 3.5
16 views
Integer division truncates toward zero when both operands are integers, so 7/2 yields 3 in PostgreSQL and most engines. Casting either operand, as in 7::numeric / 2, forces decimal arithmetic and returns 3.5. Averaging integer columns behaves similarly, which is why AVG(col) returns a numeric type while a hand-written SUM(col)/COUNT(*) may not.
Asked in: NTS, PPSC IT, Interviews
Not sure why the answer is B? Ask here and get an explanation.