Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

This is an answer to the comment, "Are they the only 2 methods? Or is their alot more? " Here are a few other ways to do it.

 where year in (1999, 2000, 2001, 2002, 2003, 2004)
 where year > 1998 and year < 2005

as suggested in Gordon's answer

where date >= {d '1999-01-01'} and date < {d '2005-01-01'}

All the answers are logically equivalent.

BETWEEN is just for the developers! The optimizer underneath still uses >= and <= anyways when it recognises a BETWEEN clause. I would prefer BETWEEN is the best approach! Reason , it gives good readability.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top