Friday, August 31, 2012

Sequence of SQL statement processed


When a query is submitted to the database, it is executed in the following order:

FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause

DECLARE
  v_job  varchar2(50);      
BEGIN
   SELECT job              
     INTO v_job
     FROM emp
    where ename='ALLEN';
        dbms_output.put_line ('Job Of this Employee iS '||v_job);
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE ('There Is An Exception'||SQLERRM);
END;
/

So why is it important to understand this?
When a query is executed, First all the tables and their join conditions are executed filtering out invalid references between them.

Then the WHERE clause is applied which again filters the records based on the condition given. Now you have handful of records which are GROUP-ed
And HAVING clause is applied on the result. As soon as it is completed, the columns mentioned are selected from the corresponding tables. And finally sorted using ORDER BY clause. So when a query is written it should be verified based on this order, otherwise it will lead wrong result sets.