T-SQL BETWEEN problem max value first

2019-02-28 08:20发布

问题:

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 AND 3

回答1:

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.



回答2:

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)