NOT IN vs NOT EXISTS

前端 未结 11 1540
粉色の甜心
粉色の甜心 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:45

    I was using

    SELECT * from TABLE1 WHERE Col1 NOT IN (SELECT Col1 FROM TABLE2)
    

    and found that it was giving wrong results (By wrong I mean no results). As there was a NULL in TABLE2.Col1.

    While changing the query to

    SELECT * from TABLE1 T1 WHERE NOT EXISTS (SELECT Col1 FROM TABLE2 T2 WHERE T1.Col1 = T2.Col2)
    

    gave me the correct results.

    Since then I have started using NOT EXISTS every where.

提交回复
热议问题