r/SQL • u/vamshidhar_522 • May 09 '26
Discussion Are left outer joins associative or not ?
( A left outer join B) left outer join C
A left outer join (B left outer join C )
Are these two results same ?
I am having trouble understanding or finding an example, can someone please help me
10
Upvotes
1
u/Sectox May 09 '26
What do you mean by associative?
6
u/kagato87 MS SQL May 09 '26
Such confusion in the thread. Probably your use of "starts with" in the question.
Your two examples will produce the same result. As will the same order with no brackets.
To really prove it out inspect the query plan. They'll all tend to produce the exact same plan.
6
u/squadette23 May 09 '26
They are not associative. Imagine non-empty A and C and empty B, with arbitrary ON conditions:
https://dbfiddle.uk/QKRFd3f_
1
u/MlecznyHotS May 09 '26
Can you elaborate on the question? Do you mean A join B join C (B=C) is the same as A join C join B (B=C)? If yes, then no those two might result in a different outcome.
3
u/Wise-Jury-4037 :orly: May 10 '26
OP, u/squadette23 right(-ish), while u/kagato87 and u/r3pr0b8 are wrong.
Hilariously enough, both ChatGPT and Gemini , basically, repeati u/squadette23's reasoning, so you could have saved yourself (and us) quite a bit of time.
It took 3 prompts 'gemini, you are wrong, find a simpler reason' for it to finally nail it down.
The simplest reason left join is not associative is that it is a context dependent function. You might have not seen it yet but join conditions can be quite complex.
So, if you have a ".... left outer join C on C.ref_b = B.id and C.ref_a = A.id" the condition would depend on both A and B being in scope. Parenthesis around (B left join C on C.ref_b = B.id and C.ref_a = A.id) would simply fail the syntax check.
But it (associativity) is not true even if you would limit the condition to just B and C.
The whole "NULL-supplying" line of reasoning is just a special case of a more generic reason: join condition for B left join C not depending on B (fully or in part).
Here's a fiddle showing that B left join C can produce rows with ids on both sides (no null rows), yet the associativity breaks (look at the a=2 row in last 2 results):
Postgres 17 | db<>fiddle
2
u/dbrownems May 09 '26
They are not the same.
fiddle
Note that the ON clause needs to change from a=c to a=b to refer to the inner table. Filtering on an outer table column can transform the outer join into an inner join. But the result is the same in this case.
1
u/r3pr0b8 GROUP_CONCAT is da bomb May 09 '26
absolutely, yes
1
u/NekkidWire May 09 '26
Outer joins are only associative if both their results don't have null values on the right side, making it moot point for using outer join in the first place.