Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FIltering on the join?

Tags:

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?

like image 806
Craig Avatar asked Feb 09 '11 03:02

Craig


People also ask

Can you filter from a join?

In an SQL query, data can be filtered in the WHERE clause or the ON clause of a join.

Does WHERE filter before or after 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.

Can we use WHERE condition in joins?

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.


2 Answers

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.

like image 81
btilly Avatar answered Sep 18 '22 00:09

btilly


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).

like image 24
HLGEM Avatar answered Sep 17 '22 00:09

HLGEM