简体   繁体   中英

Order of execution SQL

This is hypothetical code:

select table2.id,table1.email,table1.status,table2.status,table2.term,table4.description
From Table1
Join Table 2 ON  table1.id = table2.id
Join Table 3 ON  table1.id = table3.id
Left Join table4 on table4.num = table2.num
Where Concat(table2.id,(Concat(table2.year,table2.term))
   IN(Select Max(Concat(id,( Concat(year,term))))
   From table5
   Group by id)
And field1 !='abc'
And field2 !='def'
And field3 !='jkl'
Order By status,id

I want to know how this takes place. The (inner) joins will run at the same time and create one virtual table which will in turn be left joined to table #4... then the where clause will be applied on the final result set? Would this be correct?

The order of the joins depends on the DBMS's optimizer which takes into consideration of the table statistics and join the tables by the order of WHERE clauses that are most selective to least selective. That way, it is more efficient as we only scan for data that matters to us. Some DMBS like Oracle allows you to specify explicit ordering such as the ORDERED hint to bypass the optimizer's choice of ordering.

There are two parts to your question. One is how the join s are interpreted by the compiler and the second is how they are executed.

For interpretation purposes, the query is (I just changed the indentation to emphasize the order of interpretation):

From ( ( (Table1 Join
          Table2
          ON  table1.id = table2.id
         ) Join
        Table 3
        ON  table1.id = table3.id
       ) Left Join
     table4
     on table4.num = table2.num
    )

That is, the result set is determined as if the join's were done in this order:

  • Table1 to Table2
  • That result to Table3
  • That result left outer joined to Table4

This interpretation has nothing to do with the actual execution. The SQL engine determines the best order for the joins. This depends on the size of the table, the availability of the indexes, and the impact of the where clause filtering.

In MySQL, you can force the ordering by using subqueries. This also has the side-effect of materializing the intermediate results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM