views:

91

answers:

4

Hey all,

I wanted to know what is better performance-wise: to put the conditions in the JOIN? (x JOIN y on x.hi = y.hi AND ....) or maybe to put it under the WHERE, and leave the JOIN only with the crossing condition.

thanks folks

+2  A: 

This will depend on the query optimisation engine and how it breaks the query down into its logical query operators.

With MS SQL Server you can view the execution plan but normally there is no difference as the optimiser will see both ways as equivalent.

John Nolan
+1  A: 

There is a similar question on StackOverflow here.

It's largely just a matter of which syntax you prefer. My understanding is that the SQL optimizer should be able to evaluate them with little difference in performance.

Bernard Dy
It certainly does make a performance difference for some DBs. Unfortunately, he doesn't say what he's using.
Craig Stuntz
I've was burnt by Interbase many years back with this.
John Nolan
You both have good points...my answer comes from exposure to Oracle and SQL Server
Bernard Dy
A: 

I don't think either should make a performance difference (Most databases can optimize this sort of thing) but they can make a difference in the results if you are using left joins.

SELECT  a.field1
        , a.field2
        , b.field3
FROM  table1 a
LEFT JOIN table2 b
    ON a.id = b.id
WHERE    a.field5 = 'test'
        AND b.field3 = 1

SELECT  a.field1
        , a.field2
        , b.field3
FROM table1 a
LEFT JOIN table2 b
    ON a.id = b.id AND b.field3 = 1
WHERE a.field5 = 'test'

These two queries do not return the same results as the first query, by putting the conditions in the where clause instead of the join, turns the left join into an inner join.

HLGEM
I mean on the assumption that the result is the same, which one is faster?
oshafran
A: 

Well you can not use *= and =* OUTER JOIN syntax in the WHERE clause with SQL Server 2008 R2

I'd hate to see a query mixing the 2 styles

gbn
Heck you shouldn't use those even in SQL Server 2000 as they can be misinterpreted as a cross join on occasion.
HLGEM
@HLGEM: We know that of course, but now we have a good reason to justify why we say "no"
gbn
@gbn, incorrect results wasn't good enough as a justification? Sure was here.
HLGEM