What's the difference between 'not in' and 'not exists'?

前端 未结 4 1856
野的像风
野的像风 2021-02-02 15:08

What\'s the difference between not in and not exists in an Oracle query?

When do I use not in? And not exist?

4条回答
  •  滥情空心
    2021-02-02 15:45

    The difference between NOT IN and NOT EXISTS becomes clear where there are NULL values included in the result.

    For example:

    create table test_a (col1 varchar2(30 char));
    create table test_b (col1 varchar2(30 char));
    
    insert into test_a (col1) values ('a');
    insert into test_a (col1) values ('b');
    insert into test_a (col1) values ('c');
    insert into test_a (col1) values ('d');
    insert into test_a (col1) values ('e');
    
    insert into test_b (col1) values ('a');
    insert into test_b (col1) values ('b');
    insert into test_b (col1) values ('c');
    insert into test_b (col1) values (null);
    

    Note: They key difference is that test_b contains a null value.

    select * from test_a where col1 not in (select col1 from test_b);
    

    No rows returned

    select * from test_a where 
        not exists
            (select 1 from test_b where test_b.col1 = test_a.col1);
    

    Returns

    col1
    ====
    d
    e
    

提交回复
热议问题