简体   繁体   中英

SQL Query Performance Join with condition

calling all sql experts. I have the following select statement:

SELECT 1
  FROM table1 t1
  JOIN table2 t2 ON t1.id = t2.id
 WHERE t1.field = xyz

I'm a little bit worried about the performance here. Is the where clause evaluated before or after the join? If its evaluated after, is there way to first evaluate the where clause?

The whole table could easily contain more than a million entries but after the where clause it may be only 1-10 entries left so in my opinion it really is a big performance difference depending on when the where clause is evaluated.

Thanks in advance.

Dimi

You could rewrite your query like this:

SELECT 1
  FROM (SELECT * FROM table1 WHERE field = xyz) t1
  JOIN table2 t2 ON t1.id = t2.id

But depending on the database product the optimiser might still decide that the best way to do this is to JOIN table1 to table2 and then apply the constraint.

For this query:

SELECT 1
FROM table1 t1 JOIN
     table2 t2
     ON t1.id = t2.id
WHERE t1.field = xyz;

The optimal indexes are table1(field, id) , table2(id) .

How the query is executed depends on the optimizer. It is tasked with choosing the based execution plan, given the table statistics and environment.

Each DBMS has its own query optimizer. So by logic of things in case like yours WHERE will be executed first and then JOIN part of the query

As mentioned in the comments and other answers with performance the answer is always "it depends" depending on your dbms and the indexing of the base tables the query may be fine as is and the optimizer may evaluate the where first. Or the join may be efficient anyway if the indexes cover the join requirements.

Alternatively you can force the behavior you require by reducing the dataset of t1 before you do the join using a nested select as Richard suggested or adding the t1.field = xyz to the join for example

ON t1.field = xyz AND t1.id = t2.id

personally if i needed to reduce the dataset before the join I would use a cte

With T1 AS 
(
   SELECT * FROM table1
   WHERE T1.Field = 'xyz'
)
SELECT 1 
FROM T1
JOIN Table2 T2
ON T1.Id = T2.Id

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