Evaldas Buinauskas
Evaldas Buinauskas

Reputation: 14077

T-SQL JOIN between JOIN and ON

Could anyone elaborate me on what would be differences between these two?

SELECT *
FROM dbo.UserProducts AS UP
INNER JOIN dbo.Products AS P
    ON P.ProductID = UP.ProductID
INNER JOIN dbo.Industry AS I
    ON I.IndustryCode = P.IndustryCode



SELECT *
FROM dbo.UserProducts AS UP
INNER JOIN dbo.Products AS P
    INNER JOIN dbo.Industry AS I
        ON I.IndustryCode = P.IndustryCode
    ON P.ProductID = UP.ProductID

I've seen second option explained on MSDN, however I cannot find this anymore and I think it was using LEFT JOINS.

Upvotes: 1

Views: 111

Answers (2)

Hart CO
Hart CO

Reputation: 34774

There's nothing different between the two examples from a logic perspective, one is just far easier to read.

Sometimes it can actually makes sense to put all the criteria below all the joins:

SELECT *
FROM table1 a
LEFT JOIN table2 b
LEFT JOIN table3 c
  ON     a.col1 = c.col1
  ON     b.ID = c.ID

But in general it's easier to read when the criteria immediately follows the JOIN

Upvotes: 1

Blorgbeard
Blorgbeard

Reputation: 103467

The grammar for FROM explains this.

The syntax is FROM { <table_source> }.

And <table_source> can be one of several things, including <joined_table>.

And <joined_table> can consist of:

<table_source> <join_type> <table_source> ON <search_condition>

So a <table_source> can be a join to a <table_source>, which can itself be a join, etc.

Your first example is "UserProducts, joined to Products; and Products joined to Industry".

The second is "UserProducts, joined to (Products and Industry joined together)"

Upvotes: 3

Related Questions