I see this mistake come up a lot in which someone has constructed a query with OUTER joins that includes a WHERE clause. The difference is probably best explained by example, so have a look at the results of these queries:
So we have two tables we want to join, but from the vehicles table, we only want “Air” type vehicles, while from our traffic table, we still want to see all of the data. So we create a RIGHT OUTER JOIN and then throw the Type criteria in the WHERE clause. But when we look at the results, we only return 3 rows – the ones with Air type vehicles.
We take another attempt by putting the criteria in the join itself and this returns all 9 rows from the traffic table and just the 3 “Air” rows from the vehicles table. So why does that happen? In the simplest terms, when this query is evaluated by SQL, it works in the following order:
- GROUP BY
- ORDER BY
The tables are first joined and then the WHERE condition is applied. So in our first case, when we filter out the rows where v.Type = ‘Air’, 6 of those rows are NULL when we finally apply the WHERE condition. This results in no rows being returned for those 6 rows. Ultimately, this makes the behavior of the query more like an INNER JOIN, completely defeating the purpose.