What, if any, is the difference between the following?
FROM table1
LEFT JOIN table2 ON table1.key = table2.key
LEFT JOIN table3 ON table2.key = table3.key
and:
FROM table1
LEFT JOIN table2
LEFT JOIN table3
ON table2.key = table3.key
ON table1.key = table2.key
Results seem to be the same.
As there are comments and answers that say second syntax is invalid I'll clarify - SQL Server, PostgreSQL and MySQL accept both variants just fine. I also work with a platform that has it's own implementation of TSQL that translates it's own implementation into the one of the provider it's actually connected to, and the second variant is how it writes the code from visual editor by default.
After the first answer i decided to add a more complex example of the second type:
SELECT table1.Name AS MainData, table3ParentParent.Name AS AdditionalData
FROM table1
LEFT JOIN table2
JOIN table3
JOIN table3 AS table3Parent
JOIN table3 AS table3ParentParent
ON table3Parent.Parent = table3ParentParent.key
ON table3.Parent = table3Parent.key
ON table2.table3_id = table3.key
ON table1.table2_id = table2.key
I've changed the names of tables to meaningless since real ones are in Russian and wouldn't tell you anything anyway, but that's part of a query I work on right now. Also, I'd like to point out that I'm not asking advice on optimizing the query, if someone finds that it's suboptimal, I'm looking to understand if there's a practical difference to syntax, or only a cosmetical one.
The first is evaluated as:
The second is evaluated as:
So, the
LEFT JOIN
betweentable2
andtable3
is evaluated first. In the first query, it is evaluated second.Does this make a difference? In this case, I don't think there is a difference. There are some other combinations of
JOIN
s where the ordering can make a difference, in subtle edge conditions.