NOT IN vs. NOT EXISTS

  • This is a basic question which occurred to me while reading something on the usage of NOT IN and NOT EXISTS. It made me to go back and look into a query I wrote a few years go to compare differences.

    In below queries, although they both give me the same result and same processing time, I was wondering which is better (less costly) to use in such cases? Comparing a value to a list (NOT IN) or a Boolean (NOT EXISTS)?

    SELECT 
    a.AcNo, a.CustID, a.ClientName
    FROM table_1 a
    WHERE a.custID NOT IN (SELECT b.CustID FROM table_2 b WHERE b.CustID=a.CustID)


    SELECT
    a.AcNo, a.CustID, a.ClientName
    FROM table_1 a
    WHERE NOT EXISTS (SELECT b.CustID FROM table_2 b WHERE b.CustID=a.CustID)
  • Hi,

    If memory servers me in the case of EXISTS vs IN, then EXISTS works slightly better as the first occurrence of table_1 record in table_2 and it will move onto the next record to check, in IN it continues to check the whole table, not sure if it behaves the same with NOT IN and NOT EXISTS as to me it would still have to check the whole table. I've never observed a meaningful time/resource difference though.

    Thanks,

    Nic

  • Use NOT EXISTS when possible, as it allows for better execution plans.

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

  • Not exists is much atomic than sets.

    Use Not Exists.

     

    Cheers,
    John Esraelo

  • You may want to change your NOT IN to exclude the correlation.  It isn't needed and may be skewing the results...the real answer to your question is: it depends.

    EXISTS vs IN - the general belief is that EXISTS performs better.  However, that all depends on how SQL Server generates the execution plan.  NOT EXISTS vs NOT IN isn't as clear.

    However, that is not the best reason for using NOT EXISTS vs using NOT IN - the best reason to avoid NOT IN is the unexpected results of including a NULL value in the set.  If the query for NOT IN returns a NULL value then no results will be returned - where using NOT EXISTS avoids that problem.

     

    Jeffrey Williams
    “We are all faced with a series of great opportunities brilliantly disguised as impossible situations.”

    ― Charles R. Swindoll

    How to post questions to get better answers faster
    Managing Transaction Logs

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply