Home >Database >Mysql Tutorial >WHERE vs. ON Clause in JOIN Queries: When Should I Use Which for Optimal Performance?
WHERE Clause vs ON in JOIN Query: Performance Implications
When using JOIN queries in T-SQL, it's common to encounter the choice between placing filtering conditions in the WHERE clause or the ON clause. While both approaches can yield the same result set, there are subtle performance differences to consider.
Specifically, let's examine the following query:
SELECT * FROM Foo f INNER JOIN Bar b ON (b.BarId = f.BarId); WHERE b.IsApproved = 1;
Compared to:
SELECT * FROM Foo f INNER JOIN Bar b ON (b.IsApproved = 1) AND (b.BarId = f.BarId);
Both queries return identical sets of rows, but the performance characteristics differ.
In general, placing filters in the ON clause is preferred for the following reasons:
However, there are cases where placing filters in the WHERE clause is necessary:
SELECT * FROM Foo f LEFT OUTER JOIN Bar b ON (b.BarId = f.BarId) WHERE (b.IsApproved IS NULL OR b.IsApproved = 1);
Conclusion:
When performance is a concern, consider placing filtering conditions in the ON clause to optimize join operations and reduce result set size. For outer joins or OPTIONAL filtering, the WHERE clause must be used to achieve the desired filtering.
The above is the detailed content of WHERE vs. ON Clause in JOIN Queries: When Should I Use Which for Optimal Performance?. For more information, please follow other related articles on the PHP Chinese website!