Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra parenthesis changing result of formula in SQL Server 2008

In all other languages (arithmetic engines in general) putting an extra set of parenthesis around operators of same priority does not impact results. But recently in a testing project I noticed that MS SQL server changes the results in those cases. Please take a look at the query below, and let me know if you have any idea (or a setting in SQL Server administration) or any links to MSDN article explaining the behavior.

select (0.55 * 287.61 / 0.66) calc_no_parens
,(0.55 * (287.61 / 0.66)) calc_parens
,round(0.55 * 287.61 / 0.66,2) no_paren_round
,round(0.55 * (287.61 / 0.66),2) paren_round;

Results

Column  Record 1
calc_no_parens  239.6750000
calc_parens     239.67499985
no_paren_round  239.6800000
paren_round     239.67000000

To me, first two of them should return 239.675, and round should give 239.68.

like image 657
Adarsha Avatar asked Sep 17 '12 04:09

Adarsha


People also ask

What will happen if we remove parentheses from calculation in sql?

emp_id; What will happen if you remove all the parentheses from the calculation? The value displayed in the CALC_VALUE column will be lower. The value displayed in the CALC_VALUE column will be higher.

Does parenthesis matter in sql?

Parentheses are necessary only if both of the following conditions apply: The query includes three or more filter criteria statements. Note: Parentheses are located at the bottom of the query along with AND and OR operators. Except for ALTRU, parentheses are located above the "Include Records Where" box.

Why do we use [] in sql?

Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code.


1 Answers

You will get the desired result if you declare each value as Float.

DECLARE @Float1 float, @Float2 float, @Float3 float;
SET @Float1 = 0.55;
SET @Float2 = 287.61;
SET @Float3 = 0.66;

select (@Float1 * @Float2 / @Float3) calc_no_parens
,(@Float1* (@Float2/ @Float3)) calc_parens
,round(@Float1 * @Float2/ @Float3,2) no_paren_round
,round(@Float1* (@Float2/ @Float3),2) paren_round;

Output

calc_no_parens  calc_parens no_paren_round  paren_round
239.675          239.675    239.68           239.68

You may want to see this article: So-called "exact" numerics are not at all exact!

like image 109
Habib Avatar answered Oct 15 '22 09:10

Habib