SQL Server IN vs. EXISTS Performance

前端 未结 9 806
醉酒成梦
醉酒成梦 2020-11-22 05:37

I\'m curious which of the following below would be more efficient?

I\'ve always been a bit cautious about using IN because I believe SQL Server turns th

相关标签:
9条回答
  • 2020-11-22 06:33

    I'd go with EXISTS over IN, see below link:

    SQL Server: JOIN vs IN vs EXISTS - the logical difference

    There is a common misconception that IN behaves equally to EXISTS or JOIN in terms of returned results. This is simply not true.

    IN: Returns true if a specified value matches any value in a subquery or a list.

    Exists: Returns true if a subquery contains any rows.

    Join: Joins 2 resultsets on the joining column.

    Blog credit: https://stackoverflow.com/users/31345/mladen-prajdic

    0 讨论(0)
  • 2020-11-22 06:40

    Off the top of my head and not guaranteed to be correct: I believe the second will be faster in this case.

    1. In the first, the correlated subquery will likely cause the subquery to be run for each row.
    2. In the second example, the subquery should only run once, since not correlated.
    3. In the second example, the IN will short-circuit as soon as it finds a match.
    0 讨论(0)
  • 2020-11-22 06:43

    EXISTS will be faster because once the engine has found a hit, it will quit looking as the condition has proved true.

    With IN, it will collect all the results from the sub-query before further processing.

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