Harsha W
Harsha W

Reputation: 3376

SQL Operator presedence

How

SELECT 80/9*9

results 72 in SQL Server.

I followed the below link but I am getting a different answer. RedGate

Upvotes: 2

Views: 98

Answers (5)

sagi
sagi

Reputation: 40491

Mathematical Operators has the same precedence in SQL as in math.

Your query result in 72 because of implicit convertion :

80 / 9

Will result in 8, since the left value is an integer, so although you expect a result of double, the optimizer is implicitly casting the value into an integer.

You can "override" the the implicit casting by using a left double value:

80.0 / 9

Upvotes: 2

Amrita Srivastava
Amrita Srivastava

Reputation: 384

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. Here both * and / have same level of precedence.

Upvotes: 0

Tanner
Tanner

Reputation: 22753

As Juergen says, they have the same precedence and with integer division it does:

80/9 = 8 (as the remainder/decimal part is removed)

If an integer dividend is divided by an integer divisor, the result is an integer that has any fractional part of the result truncated.

Then:

8 * 9 = 72

Upvotes: 2

sticky bit
sticky bit

Reputation: 37497

80 / 9 yields 8. As both operands are integer, so is the result. / and * have the same precedence, so the expression is evaluated from left to right:

   80 / 9 * 9
-> 8 * 9
-> 72

Upvotes: 2

juergen d
juergen d

Reputation: 204924

Since * and / have the same precedence (2) it is processed from left to right one by one.

Upvotes: 1

Related Questions