What's the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?

前端 未结 5 848
独厮守ぢ
独厮守ぢ 2020-11-22 00:56

It seems to me that you can do the same thing in a SQL query using either NOT EXISTS, NOT IN, or LEFT JOIN WHERE IS NULL. For example:

SELECT a FROM table1          


        
5条回答
  •  别跟我提以往
    2020-11-22 01:10

    Assuming you are avoiding nulls, they are all ways of writing an anti-join using Standard SQL.

    An obvious omission is the equivalent using EXCEPT:

    SELECT a FROM table1
    EXCEPT
    SELECT a FROM table2
    

    Note in Oracle you need to use the MINUS operator (arguably a better name):

    SELECT a FROM table1
    MINUS
    SELECT a FROM table2
    

    Speaking of proprietary syntax, there may also be non-Standard equivalents worth investigating depending on the product you are using e.g. OUTER APPLY in SQL Server (something like):

    SELECT t1.a
      FROM table1 t1
           OUTER APPLY 
           (
            SELECT t2.a
              FROM table2 t2
             WHERE t2.a = t1.a
           ) AS dt1
     WHERE dt1.a IS NULL;
    

提交回复
热议问题