ON vs WHERE in an OUTER JOIN
The main difference is when the condition is applied:
-
ONfilters rows while joining the tables. -
WHEREfilters rows after the join result is created.
This difference is especially important for LEFT, RIGHT, and FULL OUTER JOIN.
Assume:
Employees
| EmployeeId | EmployeeName | DepartmentId |
|---|---|---|
| 1 | Arun | 10 |
| 2 | Banu | 20 |
| 3 | Charles | NULL |
Departments
| DepartmentId | DepartmentName |
|---|---|
| 10 | IT |
| 20 | HR |
Condition in the WHERE clause
SELECT
E.EmployeeName,
D.DepartmentName
FROM Employees E
LEFT JOIN Departments D
ON E.DepartmentId = D.DepartmentId
WHERE D.DepartmentName = 'IT';
Result
| EmployeeName | DepartmentName |
|---|---|
| Arun | IT |
What happened?
The LEFT JOIN initially returns all employees. But after the join, the WHERE condition removes:
-
Banu because her department is HR.
-
Charles because his department value is
NULL.
Therefore, the query effectively behaves like an INNER JOIN.
Condition in the ON clause
SELECT
E.EmployeeName,
D.DepartmentName
FROM Employees E
LEFT JOIN Departments D
ON E.DepartmentId = D.DepartmentId
AND D.DepartmentName = 'IT';
Result
| EmployeeName | DepartmentName |
|---|---|
| Arun | IT |
| Banu | NULL |
| Charles | NULL |
What happened?
The condition controls which department rows can match, but the LEFT JOIN still preserves every employee.
-
Arun matches IT.
-
Banu’s HR department does not satisfy the condition, so department data becomes
NULL. -
Charles has no department, so department data is
NULL.
Quick comparison
| Condition location | When applied | Effect on LEFT JOIN |
|---|---|---|
ON |
During the join | Preserves all left-table rows |
WHERE |
After the join | Can remove unmatched left-table rows |
WHERE ... IS NULL |
After the join | Can identify unmatched rows |
Finding employees without departments
A WHERE condition is intentionally used here:
SELECT
E.EmployeeName
FROM Employees E
LEFT JOIN Departments D
ON E.DepartmentId = D.DepartmentId
WHERE D.DepartmentId IS NULL;
This returns employees who have no matching department.
Important key point
For a LEFT JOIN:
-
Put right-table filtering conditions in
ONwhen you want to keep all left-table rows. -
Put conditions in
WHEREwhen you want to filter the final result.
A condition on the preserved table usually behaves similarly in ON and WHERE, but the result can still differ:
-- Keeps all employees, but only DepartmentId 10 can match
LEFT JOIN Departments D
ON E.DepartmentId = D.DepartmentId
AND E.DepartmentId = 10
-- Returns only employees whose DepartmentId is 10
LEFT JOIN Departments D
ON E.DepartmentId = D.DepartmentId
WHERE E.DepartmentId = 10
Interview answer:
“The ON clause controls whether rows match during the join, while the WHERE clause filters the completed result. In an outer join, filtering the non-preserved table in WHERE may remove NULL-extended rows and effectively convert the outer join into an inner join.”