Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order precedence of multiplication and division

Tags:

tsql

SELECT -1 * 100 / 10
SELECT 100 * -1 / 10

differ in result. First returns -10, second 0. Obviously it's caused by the order.

But I can't find any information that divisions have higher weighting than multiplications.

Looking at http://technet.microsoft.com/en-gb/library/ms190276%28v=sql.105%29.aspx multiplication and division are on the same level and reading on it's written

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.

Regarding this, the second query should be evaluated like this: 100 * -1 -> result / 10, shouldn't it?

like image 889
Nico Avatar asked Nov 28 '13 10:11

Nico


People also ask

Which has more precedence multiplication or division?

Multiplication has the same precedence as division, but multiplication and division have higher precedence than addition and subtraction have. The multiplication takes place first, the value is added to B, and then the result is assigned to A.

Are multiplication and division the same in order of operations?

The order of operations is a rule that tells the correct sequence of steps for evaluating a math expression. We can remember the order using PEMDAS: Parentheses, Exponents, Multiplication and Division (from left to right), Addition and Subtraction (from left to right).


1 Answers

This is either a "flaw" in the documentation or in SQL Server itself: According to your link the negative operator - has a lower operator precedence than multiplication and division, yet it has an effect on the order of the evaluation. You can see this because you are only using int values so that -1/10 results in 0. If you would use floating point arithmetics everything would be fine:

SELECT -1 * 100 / 10.0
SELECT 100 * -1 / 10.0

Or you could use variables to "hide" the negate:

DECLARE @a int
DECLARE @b int
DECLARE @c int

SELECT @a=-1, @b=100, @c=10

SELECT @a*@b/@c
SELECT @b*@a/@c

And as usual with complex arithmetics (complex means more than one operator) you can use parentheses to enforce a certain order of evaluation like @Mack mentioned in his answer.

like image 98
Ocaso Protal Avatar answered Nov 16 '22 06:11

Ocaso Protal