Is there any argument, performance wise, to do filtering in the join, as opposed to the WHERE clause?
For example,
SELECT blah FROM TableA a INNER JOIN TableB b ON b.id = a.id AND b.deleted = 0 WHERE a.field = 5
As opposed to
SELECT blah FROM TableA a INNER JOIN TableB b ON b.id = a.id WHERE a.field = 5 AND b.deleted = 0
I personally prefer the latter, because I feel filtering should be done in the filtering section (WHERE), but is there any performance or other reasons to do either method?
In an SQL query, data can be filtered in the WHERE clause or the ON clause of a join.
Normally, filtering is processed in the WHERE clause once the two tables have already been joined. It's possible, though that you might want to filter one or both of the tables before joining them. For example, you only want to create matches between the tables under certain circumstances.
To use the WHERE clause to perform the same join as you perform using the INNER JOIN syntax, enter both the join condition and the additional selection condition in the WHERE clause. The tables to be joined are listed in the FROM clause, separated by commas. This query returns the same output as the previous example.
If the query optimizer does its job, there is no difference at all (except clarity for others) in the two forms for inner joins.
That said, with left joins a condition in the join means to filter rows out of the second table before joining. A condition in the where means to filter rows out of the final result after joining. Those mean very different things.
With inner joins you will have the same results and probably the same performance. However, with outer joins the two queries would return different results and are not equivalent at all as putting the condition in the where clause will in essence change the query from a left join to an inner join (unless you are looking for the records where some field is null).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With