This question already has an answer here:
I'm experiencing a very confusing situation that makes me question all my understanding of joins in SQL Server.
SELECT t1.f2
FROM t1
LEFT JOIN t2
ON t1.f1 = t2.f1 AND cond2 AND t2.f3 > something
Does not give the same results as :
SELECT t1.f2
FROM t1
LEFT JOIN t2
ON t1.f1 = t2.f1 AND cond2
WHERE t2.f3 > something
Can please someone help by telling if this two queries are supposed to be equivalent or not?
Thx
In the first case, results in
t2
is filtered as part of the join.In the second case, there could be more rows available from
t2
.Essentially, the set of records joined in the two queries will not be the same.
It does make a difference because in second case you are applying the where AFTER it does the left join
The
on
clause is used when thejoin
is looking for matching rows. Thewhere
clause is used to filter rows after all the joining is done.An example with Disney toons voting for president:
This still returns
Romney
even thoughDonald
didn't vote for him. If you move the condition from theon
to thewhere
clause:Romney
will no longer be in the result set.Both are literally different.
The first query does the filtering of table
t2
before the joining of tables take place. So the results will then be join on tablet1
resulting all the records oft1
will be shown on the list.The second one filters from the total result after the joining the tables is done.
Here's an example
Table1
Table2
In your first query, it looks like this,
What it does is before joining the tables, the records of
table2
are filtered first by the score. So the only records that will be joined on table1 arebecause the
Score
ofT1_ID
is only 10. The result of the query isWhile the second query is different.
It joins the records first whether it has a matching record on the other table or not. So the result will be
and the filtering takes place
b.Score >= 20
. So the final result will be