I’m joining two tables on a composite key, and I’m wondering if it matters where I compare the corresponding columns when I do the join.
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).
I need to join the two tables on the key. Is there a difference between the following three (extraordinarily contrived) statements in terms of performance?
SELECT *
FROM TableA a
JOIN TableB b
ON a.ColAFoo = b.ColBFoo
AND a.ColAFoo2 = b.ColBFoo2
SELECT *
FROM TableA a
JOIN TableB b
ON a.ColAFoo = b.ColBFoo
WHERE a.ColAFoo2 = b.ColBFoo2
-- this one is a little /too/ contrived, apparently (see comments)
SELECT *
FROM TableA a
JOIN TableB b
WHERE a.ColAFoo = b.ColBFoo
AND a.ColAFoo2 = b.ColBFoo2
For an
inner jointhe following are equivelent in results, and will probably produce the same query plan:However Putting the join criteria in the
ONclause will communicate to other programmers, “Hey! This is the criteria to relate the tables together.” Versus stuff in the where clause that is, “criteria to limit the results, after the joins are done.”Also, the placement of the criteria makes a big difference in results when using an
outer join, so it is a good habit to get into to put the join criteria in theonin all cases.