I am going to bring closure to my series of very short articles or tidbits on Transaction SQL Operators. An operator is a symbol specifying an action that is performed on one or more expressions.
I will exploring the operator precedence today. In mathematics and computer programming, the order of operations is a set of rules used to clarify which procedures should be performed first in a given mathematical expression.
I do not have enough time in this very short article to go over the eight levels that group and order expression evaluation. However, I want to go over one example in which parentheses can be used to change the order of evaluation.
The first expression evaluates multiplication first since it is considered a higher level than subtraction. The second example changes the order by using parentheses.
The example script below explores all three operators.
1 2 3 4 5 6 7 8 9 |
-- -- Operator Precedence -- -- Results in 2 select x = 2*3-2*2; -- Results in 4 select 2*(3-2)*2 as y; |
The output of the above TSQL statements is listed below.
1 2 3 4 5 6 7 8 |
-- ~ OUTPUT ~ x ----------- 2 y ----------- 4 |
If your Transaction SQL code is not evaluating the programming expression as you would like, consider using parentheses. Next time I will be talking about logic functions.