Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005 'between' operator behavior - bug or feature?

According to microsoft documentation, the behavior of the 'BETWEEN' operator should be a closed interval both on the left and the right side, however, the following code:

SELECT CASE WHEN (1 BETWEEN 1 AND 2) THEN 'YEAH' ELSE 'NO' END AS [closed in the left],
       CASE WHEN (1 BETWEEN 2 AND 1) THEN 'YEAH' ELSE 'NO' END AS [closed in the right]

shows otherwise. Can you reproduce it? What do you think?

like image 220
Lynx Kepler Avatar asked Jul 28 '11 20:07

Lynx Kepler


2 Answers

The minimum value must always be specified first when using BETWEEN. The documentation you cited indicates that:

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.

so your second CASE is actually testing:

1 >= 2 AND 1 <= 1
like image 155
Joe Stefanelli Avatar answered Oct 05 '22 03:10

Joe Stefanelli


The documentation you link to says:

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

so the results you are getting are correct. The BETWEEN is simply a shorthand.

like image 27
Schroedingers Cat Avatar answered Oct 05 '22 05:10

Schroedingers Cat