Difference between EXISTS and IN in SQL?

前端 未结 21 1524
执笔经年
执笔经年 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?

    0 讨论(0)
  • 2020-11-22 17:38

    Difference lies here:

    select * 
    from abcTable
    where exists (select null)
    

    Above query will return all the records while below one would return empty.

    select *
    from abcTable
    where abcTable_ID in (select null)
    

    Give it a try and observe the output.

    0 讨论(0)
  • 2020-11-22 17:39

    If a subquery returns more than one value, you might need to execute the outer query- if the values within the column specified in the condition match any value in the result set of the subquery. To perform this task, you need to use the in keyword.

    You can use a subquery to check if a set of records exists. For this, you need to use the exists clause with a subquery. The exists keyword always return true or false value.

    0 讨论(0)
提交回复
热议问题