Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the output different in SQL Server and same in Oracle?

Why is the output of below two queries is different in SQL Server and same in Oracle ?

SELECT 20.0/-2.0/5

SELECT 20/(-2.0)/5
like image 778
Brij Avatar asked Oct 04 '22 12:10

Brij


1 Answers

I'm not agree with your statement that the output should be the same.
If you ask me what 20/-2/5 much output, I will answer you that it could output -2 or -50, depends on implementation details.

In Oracle, the only thing you know is that operators '*' and '/' are evaluated before '+' and '-'. But that's all. I don't find any documentation on the priority gives to operator '*' and '/' between themselves.
Since the two query gives -2, you can assume that the parenthesis are left over, and the calculation is made from left to right.

In SQL Server, the docs specified that

When two operators in an expression have the same operator precedence level, they are evaluated left to right based on their position in the expression.

So this computation is conform to the specs :

20/2/5 = (20/2)/5 = 2

Now add the minus sign

20/-2/5 = 20/(-2/5) = -50

Add parenthesis again

20/(-2)/5 = (20/-2)/5 = -2

So not only the parenthesis change the order, but the minus sign too.

In fact, the result should be considered as Undefined, and you can't rely on it.
Add some parenthesis for having a well defined result and prevent headache.

like image 132
Cyril Gandon Avatar answered Oct 13 '22 10:10

Cyril Gandon