sql statements with equals vs in

后端 未结 2 1690
说谎
说谎 2020-12-16 09:14

Say that someone came up to you and said we\'re going to cut down the amount of SQL that we write by replacing equals with IN. The use would be both for single

相关标签:
2条回答
  • 2020-12-16 09:54

    Those two specific statements are equivalent to the optimizer (did you compare the execution plans?), but I think the more important benefit you get out of the latter is that

    WHERE id = 1 OR id = 2 OR id = 3 OR id = 4 OR id = 5
    

    Can be expressed as the following, much more concise and readable (but semantically equivalent to the optimizer) version:

    WHERE id IN (1,2,3,4,5)
    

    The problem is that when expressed as the latter most people think they can pass a string, like @list = '1,2,3,4,5' and then say:

    WHERE id IN (@list)
    

    This does not work because @list is a single scalar string, and not an array of integers.

    For cases where you have a single value, I don't see how that "optimization" helps anything. You haven't written less SQL, you've actually written more. Can you outline in more detail how this is going to lead to less SQL?

    0 讨论(0)
  • 2020-12-16 10:00

    The two will produce the same execution plan - either a table scan, index scan, or index seek, depending on if/how you have your table indexed.

    You can see for yourself - Displaying Graphical Execution Plans (SQL Server Management Studio) - See the section called "Using the Execution Plan Options".

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