Disregarding performance, will I get the same result from query A and B below? How about C and D?
-- A
select *
from a left join b
on <blahblah>
left join c
on <blahblan>
-- B
select *
from a left join c
on <blahblah>
left join b
on <blahblan>
-- C
select *
from a join b
on <blahblah>
join c
on <blahblan>
-- D
select *
from a join c
on <blahblah>
join b
on <blahblan>
For
INNER
joins, 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
,RIGHT
orFULL
)OUTER
joins, yes, the order matters - and (updated) things are much more complicated.First, outer joins are not commutative, so
a LEFT JOIN b
is not the same asb LEFT JOIN a
Outer 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"
ON
conditions. BothON b.ab_id = a.ab_id
andc.bc_id = b.bc_id
are equality checks and do not involveNULL
comparisons.You can even have conditions with other operators or more complex ones like:
ON a.x <= b.x
orON a.x = 7
orON a.x LIKE b.x
orON (a.x, a.y) = (b.x, b.y)
and the two queries would still be equivalent.If however, any of these involved
IS NULL
or 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.for regular Joins, it doesn't.
TableA join TableB
will produce the same execution plan asTableB join TableA
(so your C and D examples would be the same)for left and right joins it does.
TableA left Join TableB
is different thanTableB left Join TableA
, BUT its the same thanTableB right Join TableA
If you try joining C on a field from B before joining B, i.e.:
your query will fail, so in this case the order matters.