SQL: Performance comparison for exclusion (Join vs Not in)

后端 未结 4 953
借酒劲吻你
借酒劲吻你 2020-12-18 03:28

I am curious on the most efficient way to query exclusion on sql. E.g. There are 2 tables (tableA and tableB) which can be joined on 1 column (col1). I want to display the d

4条回答
  •  青春惊慌失措
    2020-12-18 03:31

    I prefer to use

    Select a.Col1
    From TableA a
    Left Join TableB b on a.Col1 = b.Col1
    Where b.Col1 Is Null
    

    I believe this will be quicker as you are utilising the FK constraint (providing you have them of course)

    Sample data:

    create table #a
    (
    Col1 int
    )
    Create table #b
    (
    col1 int
    )
    
    insert into #a
    Values (1)
    insert into #a
    Values (2)
    insert into #a
    Values (3)
    insert into #a
    Values (4)
    
    insert into #b
    Values (1)
    insert into #b
    Values (2)
    
    
    Select a.Col1
    From #a a 
    Left Join #b b on a.col1 = b.Col1
    Where b.Col1 is null
    

提交回复
热议问题