With an INNER JOIN
, there is no difference, either in terms of performance or the definition of the result set. There is a difference with OUTER JOIN
s.
The WHERE
clause filters the results of the FROM
after the FROM
is evaluated. So, consider these two queries:
SELECT E.id, D.name, E.sal
from EMP E LEFT JOIN
DEP D
ON E.id = D.id
WHERE E.sal > 100;
SELECT E.id, D.name, E.sal
from EMP E LEFT JOIN
DEP D
ON E.id = D.id AND E.sal > 100;
The first filters the EMP
table to get the appropriate ids. The second does not filter the EMP
table. Why not? Well, the definition of LEFT JOIN
says to take all rows in the first table, regardless of whether the ON
finds a matching record in the second table. So, there is no filtering.
Now, consider this version:
SELECT E.id, D.name, E.sal
from EMP E RIGHT JOIN
DEP D
ON E.id = D.id
WHERE E.sal > 100;
SELECT E.id, D.name, E.sal
from EMP E RIGHT JOIN
DEP D
ON E.id = D.id AND E.sal > 100;
The first turns the RIGHT JOIN
to an INNER JOIN
. Why? Because for non-matching rows, E.sal
is NULL
and fails the WHERE
. The second version keeps all departments, even those that have no employees matching the condition. Note: I (and others) much prefer left outer joins to right outer joins in terms of following the logic. The logic for a left outer join is simple: keep all rows in the first table.
The FULL OUTER JOIN
combines these two situations.