You should always use join
when defining relations in queries: That way you'll keep relations and conditions clearly and orderly separated.
"Keep the order, and order will keep you"
JOIN
is meant to be used when defining the domain of the data set you're working for, and WHERE
is meant to be used when getting a subset of the domain you've already defined. A quick check list I make when writing queries regarding the order of the execution of a SQL SELECT
statement is:
FROM
WHERE
GROUP BY
(and aggregations)
HAVING
ORDER BY
and SELECT
(Yes, I know it's simplistic, but it helps me). This way I keep things in order: First, I have to define the source of my data set, and that includes any relations I may need. After that, I can filter my data set to suit my needs, and then I can transform it. Only then I can see my data.
Consider the following example (using the where
approach):
select e1.name as employee, e2.name as manager
from emp e1, emp e2
where e1.emp_id = e2.manager_id
and e1.departament = 'Sales' -- When you add conditions to the query things can be
-- confusing: Where the 'relations' end and the 'conditions'
-- begin?
Now, consider the same example, using join
:
select e1.name as employee, e2.name as manager
from emp e1 inner join emp e2 on e1.emp_id = e2.manager_id -- Relations are clearly
where e1.departament = 'Sales' -- separated, and you can focus
-- on filter conditions in the
-- WHERE clause
Another example: What if you need to use more than one table? If you use implicit relations (i.e. defining relations in the WHERE
clause) you'll find yourself confused very soon. And what if you need to define OUTER JOIN
s?
Bottom line: Always use JOIN
: It will help you