Wednesday 29 May 2013

ORDER BY Clause in SQL


  • Sort rows with the ORDER BY clause
    • ASC:  ascending order (Default)
    • DESC:  descending order
  • The ORDER BY clause comes last in the SELECT statement.
  • We can Sort the rows by the name of the column which may not be present in the sorted list. (see second example)
Example:

Example: Here names of employees are sorted according to salary but salary column is not present in the sorting list. 



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.