left join turns into inner join
SELECT
a.foo
b.bar
c.foobar
FROM tableOne AS a
INNER JOIN tableTwo AS b ON a.pk = b.fk
LEFT JOIN tableThree AS c ON b.pk = c.fk
WHERE a.foo = 'something'
AND c.foobar = 'somethingelse'
Having the and clause after the where clause seems to turn the left join into an inner join. The behavior i am seeing is if there isnt 'somethingelse' in tableThree there will be 0 rows returned.
If i move c.foobar = 'somethingelse' into the join clause the stored join will act like a left join.
SELECT
a.foo
b.bar
c.foobar
FROM tableOne AS a
INNER JOIN tableTwo AS b ON a.pk = b.fk
LEFT JOIN tableThree AS c ON b.pk = c.fk
AND c.foobar = 'somethingelse'
WHERE a.foo = 'something'
Can someone point me at some documentation describing why this happens? THank you very much
Solution 1:
It's because of your WHERE
clause.
Whenever you specify a value from the right side of a left join in a WHERE
clause (which is NOT NULL
), you necessarily eliminate all of the NULL
values and it essentially becomes an INNER JOIN
.
If you write, AND (c.foobar = 'somethingelse' OR c.foobar IS NULL)
that will solve the problem.
You can also move the c.foobar
portion into your join predicate, and that too will solve the issue.
Solution 2:
The reason you're seeing this is because the left join sets all columns of c
to NULL for those rows that don't exist in c
(i.e. that can't be joined). This implies that the comparison c.foobar = 'somethingelse'
is not true, which is why those rows are not being returned.
In the case where you move the c.foobar = 'somethingelse'
into the join condition, that join is still returning those rows (albeit with NULL values) when the condition is not true.
Solution 3:
The 'where' clause is performed after the join. This doesn't matter for inner joins but matters for outer joins.
Shorten Example
SELECT b.bar,c.foobar FROM tableTwo AS b LEFT JOIN tableThree AS c ON b.pk=c.fk WHERE c.foobar='somethingelse'
Raw data Outer Join Result Select Result
b.pk c.fk c.foorbar b.pk c.fk c.foorbar c.foorbar
1 1 something 1 1 something <not in result set>
1 1 somethingelse 1 1 somethingelse somethingelse
SELECT b.bar,c.foobar FROM tableTwo AS b LEFT JOIN tableThree AS c ON b.pk=c.fk AND c.foobar='somethingelse'
Raw data Outer Join Result Select Result
b.pk c.fk c.foorbar b.pk c.fk c.foorbar c.foorbar
1 1 something 1 null null null
1 1 somethingelse 1 1 somethingelse somethingelse