T-SQL BETWEEN problem max value first

前端 未结 2 1987
长发绾君心
长发绾君心 2021-01-24 11:40

Why this two expressions return different results? This is really stupid.

SELECT * FROM Table WHERE ID BETWEEN 3 AND 1

SELECT * FROM Table WHERE ID BETWEEN 1 AN         


        
相关标签:
2条回答
  • 2021-01-24 11:43

    As the documentation says:

    BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.

    Doesn't say anything about swapping the start_expression and end_expression to match min and max values. You should expect the result as documented, not as you believe it should.

    For the curious out there, the ANSI SQL99 standard specifies that the BETWEEN predicate should include a clause for SYMMETRIC or ASYMMETRIC comparison. Only the SYMMETRIC one is allowed to swap the start_range and end_range, the ASYMMETRIC one is required to be strict. The ASYMMETRIC form is the implicit form. In other words an implementation that interprets A BETWEEN X and Y as (A>=X AND A<=Y) OR (A>=Y AND A<=X), as the OP suggests, is not standard compliant.

    0 讨论(0)
  • 2021-01-24 12:08

    ID BETWEEN 3 AND 1 is simply short hand for ID >= 3 AND ID <=1 so will never return any results.

    If you look at the query plan you will see that the query text actually gets expanded out to this (Edit Or at least you can see this substitution of BETWEEN with >= / <= in queries that get auto parametrised)

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