You must Sign In to post a response.
  • Category: SQL Server

    Order of Clauses in SQL Query

    Hi,

    One interviewer asked me the order of the execution of sql clauses for example: if a sql query contains group by, having, where, order by clauses.

    SELECT ...
    FROM .....
    WHERE ........
    GROUP BY ...........
    HAVING .............
    ORDER BY ................



    Thanks in advance.
  • #649063
    Hi,

    Sequence of execition will be
    1. Where clause
    2. Group by
    3. Order by clause.

    Orde by will be the last one to execute as it is applied on the result set.


    Regards,
    Asheej T K

  • #649130
    Hi,

    Sql query Clauses :

    SELECT
    FROM
    WHERE
    GROUP BY
    HAVING
    ORDER BY

    From Clause:

    From the above clauses "From Clause" executes first.As in the From clause we know on which table we want to fire query.Once the table is known we can do our futher operations.And also it our first chance to filter the record set size as we can get filterd records by using ON condtion after From

    Check this :



    FROM table1 INNER JOIN table2 ON table1.tid1=table2.tid1



    This way, by the time we get to the WHERE clause, we will have already excluded rows where table1 and table2 id are not same.

    Where Clause:

    Where clause executes second .it is a second chance to filter the records.

    if we create a column in SELECT query and try to use it in where condition we get an error as "Unknown column in Where condition " . as that column is not refrencable in where condition because WHERE condition execute first and then SELECT will execute
    Following statement generates error:



    Select "abc" as col1 FROM table1 where col1="xyz"



    Select Clause:

    Select clause will execute after the WHERE condition and returns the result set.

    Order By Clause :

    Order by Clause execute on the result set which is return by SELECT clause and arranges the resukt set in particular order.

    If I have done some mistake please correct me.

    With Regards
    Kushal

  • #649158
    Hi,

    1. First Select Command will be executed.
    2. It includes the records which mets the condition in the WHERE Clause.
    3. Groups the Records according the conditions Set in Group by Clause.
    4. At the End Order By Clause will applied to Query Result and Then Query Output will be displayed.

    Vijayalakshmi G M
    IT Professional Trainer
    www.wincorporatetraining.com

  • #649167
    Hello,

    The order in which SQL directives get executed:

    1.FROM clause
    2.WHERE clause
    3.GROUP BY clause
    4.HAVING clause
    5.ORDER BY clause

    Regards
    Mr.Rajesh
    Software Engg.


  • This thread is locked for new responses. Please post your comments and questions as a separate thread.
    If required, refer to the URL of this page in your new post.