SQL Filter criteria in join criteria or where clause which is more efficient

后端 未结 9 1672
攒了一身酷
攒了一身酷 2020-12-03 02:47

I have a relatively simple query joining two tables. The \"Where\" criteria can be expressed either in the join criteria or as a where clause. I\'m wondering which is more

9条回答
  •  广开言路
    2020-12-03 03:34

    I don't think you'll find a finite answer for this one that applies to all cases. The 2 are not always interchangeable - since for some queries (some left joins) you will come up with different results by placing the criteria in the WHERE vs the FROM line.

    In your case, you should evaluate both of these queries. In SSMS, you can view the estimated and actual execution plans of both of these queries - that would be a good first step in determining which is more optimal. You could also view the time & IO for each (set statistics time on, set statistics io on) - and that will also give you information to make your decision.

    In the case of the queries in your question - I'd bet that they'll both come out with the same query plan - so in this case it may not matter, but in others it could potentially produce different plans.

    Try this to see the difference between the 2...

    SET STATISTICS IO ON
    SET STATISTICS TIME ON
    
    select salesman.salesmanid, 
           max(sales.quantity)
    from   salesmaninner join sales on salesman.salesmanid =sales.salesmanid
           and sales.salesdate < salesman.promotiondate
    group by salesman.salesmanid
    
    select salesman.salesmanid, 
           max(sales.quantity)
    from   salesmaninner join sales on salesman.salesmanid = sales.salesmanid 
    where  sales.salesdate < salesman.promotiondate
    group by salesman.salesmanid
    
    SET STATISTICS TIME OFF
    SET STATISTICS IO OFF
    

提交回复
热议问题