Example 1:
FROM
table1
LEFT JOIN table2 ON
table1.id = table2.id
AND
table2.flag = TRUE
Example 2:
FROM
table1
LEFT JOIN table2 ON
table1.id = table2.id
WHERE
table2.flag = TRUE
Q1: Will both of these return the same number of rows? If not, why?
Q2: Which one is better?
3
Answers
No, they will not produce(might not) same result.
As soon as you use a column from your
LEFT JOIN
ed table in where clause it acts like theLEFT
part will not be considered.As per your 2nd question,
Which one is better
, This is not a matter of better or worse, it totally depends on what your need of result is.Here is an example
Create table1
Your schema is now ready, Now try the following query:
Query 1
No, the number of rows that Example 1 and Example 2 return isn’t ensured to be equal. Even though there isn’t a match that meets the requirement in the right table, Example 1 still contains all of the rows from the left table. Whereas in case of example 2 Only the rows where the condition is met are included.
In answer of your second question, depending on whether you want to include all rows from the left table (Example 1) or only rows where the condition is satisfied (Example 2), you can choose between Example 1 and Example 2. Make your selection depending on your unique needs.
Hope it’s helpful 🙂
The Both Queries are not equivalent.
Because the first query will select all the records from first table and joins the rows from second table if they fulfill the joining condition. and will not skip any row from table1
While the second query will skip all the records which do not fulfill the where clause. In this second case the join will work like an inner join. [i.e if the rows fulfilling the joining condition exist in both tables then select else skip].