Difference between EXISTS and IN in SQL?

前端 未结 21 1522
执笔经年
执笔经年 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:31

    My understand is both should be the same as long as we are not dealing with NULL values.

    The same reason why the query does not return the value for = NULL vs is NULL. http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/

    As for as boolean vs comparator argument goes, to generate a boolean both values needs to be compared and that is how any if condition works.So i fail to understand how IN and EXISTS behave differently .

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

    The reason is that the EXISTS operator works based on the “at least found” principle. It returns true and stops scanning table once at least one matching row found.

    On the other hands, when the IN operator is combined with a subquery, MySQL must process the subquery first, and then uses the result of the subquery to process the whole query.

    The general rule of thumb is that if the subquery contains a large volume of data, the EXISTS operator provides a better performance.

    However, the query that uses the IN operator will perform faster if the result set returned from the subquery is very small.

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

    EXISTS will tell you whether a query returned any results. e.g.:

    SELECT * 
    FROM Orders o 
    WHERE EXISTS (
        SELECT * 
        FROM Products p 
        WHERE p.ProductNumber = o.ProductNumber)
    

    IN is used to compare one value to several, and can use literal values, like this:

    SELECT * 
    FROM Orders 
    WHERE ProductNumber IN (1, 10, 100)
    

    You can also use query results with the IN clause, like this:

    SELECT * 
    FROM Orders 
    WHERE ProductNumber IN (
        SELECT ProductNumber 
        FROM Products 
        WHERE ProductInventoryQuantity > 0)
    
    0 讨论(0)
  • 2020-11-22 17:33

    EXISTS Is Faster in Performance than IN. If Most of the filter criteria is in subquery then better to use IN and If most of the filter criteria is in main query then better to use EXISTS.

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

    I found that using EXISTS keyword is often really slow (that is very true in Microsoft Access). I instead use the join operator in this manner : should-i-use-the-keyword-exists-in-sql

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

    As per my knowledge when a subquery returns a NULL value then the whole statement becomes NULL. In that cases we are using the EXITS keyword. If we want to compare particular values in subqueries then we are using the IN keyword.

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