NOT IN vs NOT EXISTS

前端 未结 11 1661
粉色の甜心
粉色の甜心 2020-11-21 12:08

Which of these queries is the faster?

NOT EXISTS:

SELECT ProductID, ProductName 
FROM Northwind..Products p
WHERE NOT EXISTS (
    SELECT 1 
    FROM         


        
11条回答
  •  无人及你
    2020-11-21 12:33

    Also be aware that NOT IN is not equivalent to NOT EXISTS when it comes to null.

    This post explains it very well

    http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/

    When the subquery returns even one null, NOT IN will not match any rows.

    The reason for this can be found by looking at the details of what the NOT IN operation actually means.

    Let’s say, for illustration purposes that there are 4 rows in the table called t, there’s a column called ID with values 1..4

    WHERE SomeValue NOT IN (SELECT AVal FROM t)
    

    is equivalent to

    WHERE SomeValue != (SELECT AVal FROM t WHERE ID=1)
    AND SomeValue != (SELECT AVal FROM t WHERE ID=2)
    AND SomeValue != (SELECT AVal FROM t WHERE ID=3)
    AND SomeValue != (SELECT AVal FROM t WHERE ID=4)
    

    Let’s further say that AVal is NULL where ID = 4. Hence that != comparison returns UNKNOWN. The logical truth table for AND states that UNKNOWN and TRUE is UNKNOWN, UNKNOWN and FALSE is FALSE. There is no value that can be AND’d with UNKNOWN to produce the result TRUE

    Hence, if any row of that subquery returns NULL, the entire NOT IN operator will evaluate to either FALSE or NULL and no records will be returned

提交回复
热议问题