Disregarding performance, will I get the same result from query A and B below? How about C and D?
----- Scenario 1:
-- A (left join)
select *
from a left join b
on <blahblah>
left join c
on <blahblan>
-- B (left join)
select *
from a left join c
on <blahblah>
left join b
on <blahblan>
----- Scenario 2:
-- C (inner join)
select *
from a join b
on <blahblah>
join c
on <blahblan>
-- D (inner join)
select *
from a join c
on <blahblah>
join b
on <blahblan>
For
INNERjoins, no, the order doesn’t matter. The queries will return same results, as long as you change your selects fromSELECT *toSELECT a.*, b.*, c.*.For (
LEFT,RIGHTorFULL)OUTERjoins, yes, the order matters – and (updated) things are much more complicated.First, outer joins are not commutative, so
a LEFT JOIN bis not the same asb LEFT JOIN aOuter joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:
is equivalent to:
but:
is not equivalent to:
Another (hopefully simpler) associativity example. Think of this as
(a LEFT JOIN b) LEFT JOIN c:This is equivalent to
a LEFT JOIN (b LEFT JOIN c):only because we have “nice”
ONconditions. BothON b.ab_id = a.ab_idandc.bc_id = b.bc_idare equality checks and do not involveNULLcomparisons.You can even have conditions with other operators or more complex ones like:
ON a.x <= b.xorON a.x = 7orON a.x LIKE b.xorON (a.x, a.y) = (b.x, b.y)and the two queries would still be equivalent.If however, any of these involved
IS NULLor a function that is related to nulls likeCOALESCE(), for example if the condition wasb.ab_id IS NULL, then the two queries would not be equivalent.