Sunday, April 17, 2011

SQL server order of precedence


Anyone who has been writing queries must have come across a situation where somehow the query looks fine but the result is not matching to the expectation. Well then one major problem here is that you are not aware of the logical or arithmetic operator sequence. I have tried to simplify, present to you the order that you should have in mind.



1~ (Bitwise NOT)
2* (Multiply), / (Division), % (Modulo)
3+ (Positive), - (Negative), + (Add), (+ Concatenate), - (Subtract), & (Bitwise AND), ^ (Bitwise Exclusive OR), | (Bitwise OR)
4=, >, <, >=, <=, <>, !=, !>, !< (Comparison operators)
5NOT
6AND
7ALL, ANY, BETWEEN, IN, LIKE, OR, SOME
8= (Assignment)



for everyone’s reference if any query has 2 operators with the sample level of precedence then the operator is evaluated from left 2 right as rule of thumb, to override this you can use brackets to increase precedence. 
Hold Up