views:

19

answers:

3

(this question is very similar to my previous question Does it matter where I check part of a composite key when joining two tables in SQL Server?)

I'm joining three tables on a composite key, with the value of one of the columns being determined by user input. I'm wondering if it matters where I compare the corresponding columns when I do the joins.

Say I have a table, TableA, with columns ColAFoo, ColAFoo2, and ColABar. TableA has a composite primary key comprising ColAFoo and ColAFoo2 (PK_TableA).

I also have TableB, with ColBFoo, ColBFoo2, and ColBOther. TableB's columns ColBFoo and ColBFoo2 comprise a foreign key to TableA's primary key (FK_TableA_TableB).

Finally, I have TableC, with ColCFoo, ColCFoo2, ColCBlah, and ColCBlah2. TableC's columns ColCFoo and ColCFoo2 comprise a foreign key to TableA's primary key (FK_TableA_TableC). I'll also say that TableC has a composite primary key comprising ColCFoo, ColCFoo2, and ColCBlah.

I need to join the three tables on the key. Is there a difference between the following (contrived) statements in terms of performance?

SELECT *
  FROM TableA a
  JOIN TableB b
    ON  a.ColAFoo = b.ColBFoo
        AND a.ColAFoo2 = b.ColBFoo2
  JOIN TableC c
    ON  a.ColAFoo = c.ColCFoo
        AND a.ColAFoo2 = c.ColCFoo2
  WHERE a.ColAFoo2 = @userInput

SELECT *
  FROM TableA a
  JOIN TableB b
    ON  a.ColAFoo = b.ColBFoo
        AND a.ColAFoo2 = b.ColBFoo2
  JOIN TableC c
    ON  a.ColAFoo = c.ColCFoo
  WHERE a.ColAFoo2 = @userInput
        AND c.ColCFoo2 = @userInput

SELECT *
  FROM TableA a
  JOIN TableB b
    ON  a.ColAFoo = b.ColBFoo
  JOIN TableC c
    ON  a.ColAFoo = c.ColCFoo
  WHERE a.ColAFoo2 = @userInput
        AND b.ColBFoo2 = @userInput
        AND c.ColCFoo2 = @userInput
+2  A: 

No. The query optimiser will recognise if these are all the same.

Best thing to do with this sort of question is just to look at the estimated execution plans and see if there are any differences.

Martin Smith
+2  A: 

No, this should results in the same execution plan. Run all 3 queries and see what the execution plan shows

SQLMenace
+1  A: 

As others said, they should be the same

However, I'd use the first one for clarity

gbn
Agreed on clarity.
stack