• vsamantha35 - Thursday, December 14, 2017 4:08 AM

    Hi All,

    Trying to understand how does below sql stmt gets executed. The reason why I am asking is , I can do inline queries if filters conditions are executed first.
    Here in the below sample sql stmt and trying to understand how does the execution, happen? below is my undertanding. Correct me, if I am wrong.

    select
      t1.c1,
      t2.c2,
      t3.c4
     from t1 inner join t2 on t1.c1 = t2.c2
     inner join t3 on t1.c3 = t3.c3 and t3.c4 = t2.c4 --join condition
    where t1.c5 in (10,20,30) --filter condition
    and t2.c4 in (Select cval from #tmp);
    order by t2.c2

    - table t1 gets loaded into memory
    - table t2 gets loaded into memory
    - table t3 gets loaded into memory
    - join happens in between t1 and t2
    - join happens between ( t1+t2 result) & t3
    - next filtering happens i,e t1.c5 and t2.c4 predicates gets executed
    - Finally, sorting i,e, order by gets executed and the end result is sent back to client app.

    or else, filters happens first before join operation???? please confirm,

    other thing is that, Does it make a difference if I keep the table which is returning/filtering rows and then doing a join to other joining tables?

    Thanks,

    Sam

    If it is the logical processing order you are looking for, Microsoft documents it as:
    FROM
    ON
    JOIN
    WHERE
    GROUP BY
    WITH CUBE or WITH ROLLUP
    HAVING
    SELECT
    DISTINCT
    ORDER BY
    TOP

    There can be some queries that stray from that general order but that wouldn't be too common. You can find Microsoft's documentation on this in the following:
    SELECT (Transact-SQL)

    Sue