When coding SQL joins, is there any difference in where you code your filtering predicates? We know that when you code SQL using the ANSI-92 syntax, the join predicate must be coded as part of the ON clause. But the filtering predicates can be coded as part of the ON or the WHERE clauses.
This ANSI-92 syntax is best for a couple of reasons:
- You can never have an orphan table that is not being joined to, thus avoiding cartesian joining. Also called cross joins.
- Separates the join relationship logic in the ON clause from the filtering logic in the WHERE clause.
Many say this is cleaner and easier to read and understand.
But what about seeing a filtering predicate as part of the ‘ON’ clause? When it comes to inner joins, I have not seen a difference in logic or performance depending on where the filtering predicates are placed. But I do not like to say ‘always’ or ‘never’ as there may be an example somewhere. In IBM documentation it states: ‘ For inner joins, ON clause predicates can supply the join condition and local filtering, and they are semantically equivalent to WHERE clause predicates’.
For example, the following 2 queries are identical.
Provide a list of the department female managers: If you run explains on the two queries, you will identical execution plans.
SELECT D.DEPTNO, D.DEPTNAME,
D.MGRNO, E.LASTNAME
FROM DEPT D INNER JOIN EMP E
ON D.MGRNO = E.EMPNO
AND E.SEX = ‘F’
;
SELECT D.DEPTNO, D.DEPTNAME,
D.MGRNO, E.LASTNAME
FROM DEPT D INNER JOIN EMP E
ON D.MGRNO = E.EMPNO
WHERE E.SEX = ‘F’
;