Search code examples
sqlsql-server-2008inner-joinwhere-clause

Condition on main table in inner join vs in where clause


Is there any reason on an INNER JOIN to have a condition on the main table vs in the WHERE clause?

Example in INNER JOIN:

SELECT 
   (various columns here from each table)
FROM dbo.MainTable AS m
INNER JOIN dbo.JohnDataRecord AS jdr
    ON m.ibID = jdr.ibID
    AND m.MainID = @MainId -- question here
    AND jdr.SentDate IS NULL
LEFT JOIN dbo.PTable AS p1
    ON jdr.RecordID = p1.RecordID
LEFT JOIN dbo.DataRecipient AS dr
    ON jdr.RecipientID = dr.RecipientID
(more left joins here)
WHERE
    dr.lastRecordID IS NOT NULL;

Query with condition in WHERE clause:

SELECT 
   (various columns here from each table)
FROM dbo.MainTable AS m
INNER JOIN dbo.JohnDataRecord AS jdr
    ON m.ibID = jdr.ibID
    AND jdr.SentDate IS NULL
LEFT JOIN dbo.PTable AS p1
    ON jdr.RecordID = p1.RecordID
LEFT JOIN dbo.DataRecipient AS dr
    ON jdr.RecipientID = dr.RecipientID
(more left joins here)
WHERE
    m.MainID = @MainId -- question here
    AND dr.lastRecordID IS NOT NULL;

Difference in other similar questions that are more general whereas this is specific to SQL Server.


Solution

  • In the scope of the question,

    Is there any reason on an INNER JOIN to have a condition on the main table vs in the WHERE clause?

    This is a STYLE choice for the INNER JOIN.


    From a pure style reflection point of view:

    While there is no hard and fast rule for STYLE, it is generally observed that this is a less often used style choice. For example that might generally lead to more challenging maintenance such as if someone where to remove the INNER JOIN and all the subsequent ON clause conditions, it would effect the primary table result set, OR make the query more difficult to debug/understand when it is a very complex set of joins.

    It might also be noted that this line might be placed on many INNER JOINS further adding to the confusion.