DEV Community

roadpilot
roadpilot

Posted on

SQL "BETWEEN" Operator

Take the following query directive:
"Query the sum of Northern Latitudes (LAT_N) from STATION having values greater than 38.7880 and less than 137.2356."

Imagine you have a table that has multiple records of stations with northern latitudes of various values - some above, some below, and some within the criteria range. For testing purposes, all edge cases will be represented. There may even be some values that are exactly at the critera range values. Remember the criteria is "greater than" and "less than".

You have two choices:

1. To write your query to include a combination condition (where statement), such as:

"select sum(lat_n) from station
WHERE lat_n > 38.7880
AND lat_n < 137.2356"

2. Or you could use "BETWEEN"

"select sum(lat_n) from station
WHERE lat_n BETWEEN 38.7880 AND 137.2356"
*** BETWEEN can be a comparison operator for number, text or date values. You can even find the inverse of the range with NOT BETWEEN

Syntactically, #2 is cleaner and a little bit more readable. But are they exactly identical?

BETWEEN is "inclusive" - the result will include the criteria, if it exists. It is essentially "greater than or equal to (>=)" and "less than or equal to (<=)". They are not identical solutions.

You could "manually" alter the range beginning and ending but you would need to know the exact level of specificity of the decimal in the data field. You could just add "1" and make the beginning of the range 39.7880 but that would still leave everything between 38.7881 and 39.7879 values that should be included in the result but won't be. You could add 1 to the last decimal and make the beginning of the range 38.7881 but then you would miss 38.78805, if it were to exist. Unless you know the specificity of the data, this kind of manual alteration really could produce inaccurate results.

I'm thinking, unless you want the results to be inclusive of the range, my rule of thumb will be to use the combination where statement using "greater than (>)" and "less than (<)". If the result needs to return values greater than 38.7880, then that could be anything from 38.7881 or 39 or even 38.7880000000000001. I can easily make this approach "inclusive" if I want to. Just knowing that "BETWEEN" is inclusive will make me be more careful about choosing to use it.

Top comments (0)