Difference between EXISTS and IN in SQL?

前端 未结 21 1745
执笔经年
执笔经年 2020-11-22 16:50

What is the difference between the EXISTS and IN clause in SQL?

When should we use EXISTS, and when should we use IN

21条回答
  •  臣服心动
    2020-11-22 17:38

    I'm assuming you know what they do, and thus are used differently, so I'm going to understand your question as: When would it be a good idea to rewrite the SQL to use IN instead of EXISTS, or vice versa.

    Is that a fair assumption?


    Edit: The reason I'm asking is that in many cases you can rewrite an SQL based on IN to use an EXISTS instead, and vice versa, and for some database engines, the query optimizer will treat the two differently.

    For instance:

    SELECT *
    FROM Customers
    WHERE EXISTS (
        SELECT *
        FROM Orders
        WHERE Orders.CustomerID = Customers.ID
    )
    

    can be rewritten to:

    SELECT *
    FROM Customers
    WHERE ID IN (
        SELECT CustomerID
        FROM Orders
    )
    

    or with a join:

    SELECT Customers.*
    FROM Customers
        INNER JOIN Orders ON Customers.ID = Orders.CustomerID
    

    So my question still stands, is the original poster wondering about what IN and EXISTS does, and thus how to use it, or does he ask wether rewriting an SQL using IN to use EXISTS instead, or vice versa, will be a good idea?

提交回复
热议问题