Logical Query Processing

  • Dear all,

    It was my understanding that when processing a query the order in which it is processed is FROM, JOIN, ON, WHERE, GROUP BY etc. This is also shown in Inside Microsoft SQL Server 2008: T-SQL Querying by Itzik Ben-Gan. However, the query below only runs successfully with the WHERE clause -

    SELECT

    SC.i5_n_oor

    , EC.CountryName

    FROM

    extract.i5_5_synd_clm AS SC

    INNER JOIN

    extract.i1_o_event AS E

    ON

    SC.i5_c_evt = E.i1_c_event

    INNER JOIN

    load.t_Dim_Country AS EC

    ON

    SUBSTRING(E.i1_s_event,CHARINDEX(',',E.i1_s_event) + 2, (CHARINDEX(' - ',E.i1_s_event) - CHARINDEX(',',E.i1_s_event)) - 2) = EC.CountryName

    WHERE

    CHARINDEX(', ',E.i1_s_event) > 0

    AND CHARINDEX(' - ',E.i1_s_event) > 0

    AND CHARINDEX(', ',E.i1_s_event) < CHARINDEX(' - ',E.i1_s_event)

    If I remove the WHERE clause I get the following error -

    Invalid length parameter passed to the LEFT or SUBSTRING function.

    So it seems it is processing the WHERE clause before the JOIN.

    Could someone please tell me what is happening? What is the order in which this query is being processed?

    Thanks in advance

  • The logical processing order specifies a way how the results should be achieved.

    However, the query processor can choose any ordering it wants, as long as the end result is the same as the one of the logical processing order.

    In some cases the order is different and SQL Server does something that leads to an error, which shouldn't be there if the logical order was followed. In this case it will execute the LEFT and SUBSTRING functions first, before the JOINS and the WHERE clauses, instead of at the end in the SELECT.

    I had a similar issue like you once, and I believe I added an index to force some other order. Or you can rewrite your query a bit.

    Need an answer? No, you need a question
    My blog at https://sqlkover.com.
    MCSE Business Intelligence - Microsoft Data Platform MVP

  • Thank you very much, that explains it!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply