Home > Database > Mysql Tutorial > Is MS SQL Server's `BETWEEN` Operator Inclusive or Exclusive?

Is MS SQL Server's `BETWEEN` Operator Inclusive or Exclusive?

DDD
Release: 2024-12-27 21:41:14
Original
178 people have browsed it

Is MS SQL Server's `BETWEEN` Operator Inclusive or Exclusive?

Inclusive Range Retrieval with MS SQL Server's "BETWEEN" Operator

When using MS SQL Server's "BETWEEN" operator, it's essential to understand whether the range boundaries are included or excluded in the selection criteria.

To answer the specific question, the "BETWEEN" operator is inclusive. This means that, by default, the values specified as the lower and upper bounds are included in the result set. In the example provided:

SELECT foo
FROM bar
WHERE foo BETWEEN 5 AND 10
Copy after login

The query will select all rows where the value of the "foo" column is between (and including) 5 and 10.

However, this inclusive behavior can present a caveat when working with DateTimes. By default, when only a date is specified, SQL Server treats it as midnight on that day. This means that if you want to capture all values within a specific day, you must subtract 3 milliseconds from the end date to avoid missing data falling within the 3 milliseconds before midnight.

For example, to retrieve all values within June 2016, the correct query would be:

where myDateTime between '20160601' and DATEADD(millisecond, -3, '20160701')
Copy after login

This ensures that you capture all values within June 2016, including those falling within the 3 milliseconds before midnight on June 30th.

It's important to note that, while for most data types the "BETWEEN" operator is inclusive, there are exceptions. For instance, with "datetime2" and "datetimeoffset" data types, it's generally recommended to use the ">=" and "<" operators instead of "BETWEEN" to avoid potential range truncation issues.

The above is the detailed content of Is MS SQL Server's `BETWEEN` Operator Inclusive or Exclusive?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template