SQL performance of filter in join vs in results where

295 Views Asked by At

I need to join 2 tables but one of them has a constant filter that has to be applied, my question is what option is better in terms of performance:

  1. Having the constant filter on the "FROM" and setting an alias like this:

     SELECT <result fields> 
     FROM 
         (SELECT <table A fields> 
          FROM filtered_table 
          WHERE field = value) AS A 
     LEFT OUTER JOIN tableB ON A.id = tableB.id
    
  2. Setting the filter in the WHERE of the main query:

    SELECT <result fields> 
    FROM filtered_table AS A 
    LEFT OUTER JOIN tableB ON A.id = tableB.id 
    WHERE a.field = value
    
1

There are 1 best solutions below

0
Gordon Linoff On

Most databases will treat the two forms the same -- they are logically the same and the optimizer knows this.

Some databases tend to materialize subqueries. MySQL is one of these. In that database, the subquery would probably be more expensive, because it writes out the subquery.

I would recommend writing the code without a subquery. It is both simpler to write and read and it should never have worse performance than the subquery method.