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

后端 未结 9 1513
攒了一身酷
攒了一身酷 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

    One thing I want to say finally as I notified, before that.. Both ways may give the same performance or using the criteria at Where clause may be little faster as found in some answers..

    But I identified one difference, you can use for your logical needs..

    1. Using the criteria at ON clause will not filter/skip the rows to select instead the join columns would be null based on the conditions

    2. Using the criteria at Where clause may filter/skip the rows at the entire results

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-03 03:34

    Case 1 (criteria in the JOIN) is better for encapsulation, and increased encapsulation is usually a good thing: decreased copy/paste omissions to another query, decreased bugs if later converted to LEFT JOIN, and increased readability (related stuff together and less "noise" in WHERE clause). In this case, the WHERE clause only captures principal table criteria or criteria that spans multiple tables.

    0 讨论(0)
提交回复
热议问题