Wednesday, 29 May 2013

Operator Precedence in SQL


  • The rules of precedence determines the order in which expressions are evaluated and calculated.
  • The table below lists the default order of precedence.
  • You can override the default order by using parentheses around the expressions you want to calculate first.

   ORDER EVALUATED                     OPERATOR

                   1                                        Arithmetic Operator
                   2                                        Concatenation Operator
                   3                                        Comparison Conditions
                   4                                        IS [NOT] NULL, LIKE, [NOT] IN
                   5                                        [NOT] BETWEEN
                   6                                        NOT logical condition
                   7                                        AND logical condition
                   8                                        OR logical condition

NOTE:

Override rules of precedence by using parentheses.

Example:  (Carefully study both the scenario in the example)


1) In the first scenario first AND operator is calculated and then the result is operated with OR.
2) In the second scenario first OR operator is calculated because of Parentheses and then result is operated with AND.


NOT Operator in SQL

Example:

The above example displays the name,job of employee whose job is not MANAGER or ANALYST.

Note:
The NOT operator can also be used with other SQL operators, such as BETWEEN, LIKE and NULL

-------- WHERE sal NOT BETWEEN 1000 AND 3000
-------- WHERE ename NOT LIKE '%K%'
-------- WHERE comm IS NOT NULL



OR Operator in SQL


  • OR requires either conditions to be TRUE. (i.e. any one condition should be satisfied)
Example:

In the above example either conditions can be true for any record to be selected. The employee can have sal >=2000 or his/her department number may be 10 or 20.

AND Operator in SQL


  • AND requires both conditions to be TRUE.
Example:

In the above example the results shown satisfies both the conditions to be displayed.