Combining datasets with EXCEPT versus checking on IS NULL in a LEFT JOIN

前端 未结 1 1155
滥情空心
滥情空心 2020-12-20 19:40

I\'m currently working my way through the Microsoft SQL Server 2008 - Database Development (MCTS Exam 70-433) certification. In one of the earlier chapters on C

相关标签:
1条回答
  • 2020-12-20 20:28

    The 2 queries will be different in cases where the LEFT JOIN gives multiple rows. That is, FactResellerSales is a child of DimEmployee with many rows per rows in DimEmployee. So you need DISTINCT as you noted for your JOIN example.

    If you change the query to use NOT EXISTS you get the same plan (left anti semi join is typical for NOT EXISTS)

    SELECT EmployeeKey
    FROM DimEmployee DE 
    WHERE
    NOT EXISTS (SELECT * FROM 
            FactResellerSales FRS
        WHERE FRS.EmployeeKey = DE.EmployeeKey)
    

    In addition and for the same reason, INTERSECT/EXISTS will most likely give the same plan.

    It's another aspect to the JOIN/EXISTS/IN or OUTER JOIN/NOT EXISTS/NOT IN debates. INTERSECT/EXCEPT is a slightly more elegant construct of (NOT) EXISTS is you like

    Edit:

    There isn't an obvious question...

    Personally, I don't use OUTER JOIN for "existence" checking: I use EXISTS or NOT EXISTS (or INTERSECT/EXCEPT if I remember) because it's more obvious what you're trying to do. AKA, if I don't need rows from the "outer" table, I don't use it to avoid having a DISTINCT.

    There is no CASE to use OUTER JOIN/IS NULL IMHO if in this case. Of course, I use OUTER JOIN when needed: this answer is for one specific case only.

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