Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct method of BETWEEN in SQL

Tags:

sql

between

What is the correct method of using between, because treehouse and my teacher have different answers for this question.

Select all movies from the years 1999 to 2004.

Treehouse answer:

SELECT * FROM movies WHERE year BETWEEN 1999 AND 2004;

Teachers answer:

SELECT * FROM movies WHERE year >= 1999 AND year <= 2004;

Which method is correct?

like image 440
AdzT1 Avatar asked Jun 10 '26 08:06

AdzT1


1 Answers

Both are technically correct. However, there are reasons to avoid using between as your teacher suggests. The simplest is that in English, the word is ambiguous and can include the end points or not. In fact, if you say that a point on a line is between two other points, the meaning is generally that the point does not coincide either end point.

This is a minor issue for integers. It becomes much more important with other data types. A particular issue is with date times. If you have a datetime field in the database, then the following does not work the way you expect:

where datetimefield between '2013-01-01' and '2013-01-02'

This will return all datetime values from 2013-01-01. Plus, it will return a datetime value that is at exactly midnight between the two dates. It will not return any other value from 2013-01-02.

I am heartened that your teacher recognizes the shortcomings of between. I hope s/he also explains why the explicit comparison method is better.

EDIT:

By the way, something similar happens for strings as well. So:

where charfield between 'a' and 'b'

will return all values that start with 'a' and exactly 'b'. But not 'ba' or 'b1'. One way to write it is:

where charfield >= 'a' and charfield < 'c'

The point is. between is a perfectly valid SQL construct. It works "correctly" for all data types. However, what is correct for SQL may not be intuitive for most people. Explicit comparisons come closer to avoiding this problem.

like image 108
Gordon Linoff Avatar answered Jun 13 '26 00:06

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!