Sub topic 8
Ranges and lists with BETWEEN and IN
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query, that you know the comparison operators (=, <>, <, <=, >, >=), and that you can combine conditions with AND, OR, and NOT. Examples use an employees table with the columns first_name, last_name, department, salary, hire_date, and manager_id.
BETWEEN and IN are shorthand. Each one replaces a longer chain of comparisons you already know how to write. They return the same rows as the long form. Their value is that the query is shorter and easier to read, and that some mistakes are harder to make.
BETWEEN: an inclusive range
BETWEEN low AND high tests whether a value falls inside a range. It is exactly equal to value >= low AND value <= high.
SELECT first_name, salary
FROM employees
WHERE salary BETWEEN 40000 AND 60000;This returns employees paid 40000, 60000, or anything in between. Both ends are included. That is the most important fact about BETWEEN, and the one people most often forget.
The two queries below are equivalent:
SELECT first_name, salary
FROM employees
WHERE salary >= 40000 AND salary <= 60000;The low value must come first
BETWEEN 60000 AND 40000 does not swap the bounds for you. It expands to salary >= 60000 AND salary <= 40000, which no row can satisfy. You get an empty result and no error. If a query that should return rows returns none, check the order of the bounds.
Using NOT BETWEEN
Put NOT before BETWEEN to select rows outside the range.
SELECT first_name, salary
FROM employees
WHERE salary NOT BETWEEN 40000 AND 60000;This is the same as salary < 40000 OR salary > 60000. Note that the AND inside BETWEEN belongs to BETWEEN. It is not a logical AND joining two separate conditions.
BETWEEN with dates and text
BETWEEN works with any type that has an ordering: numbers, dates, and text.
SELECT first_name, hire_date
FROM employees
WHERE hire_date BETWEEN '2020-01-01' AND '2022-12-31';Dates written as 'YYYY-MM-DD' strings are accepted by PostgreSQL, MySQL, and SQLite. In SQLite, dates are stored as text, so this works only if every stored value uses that same format.
With text, the comparison follows the database's sorting rules (its collation). last_name BETWEEN 'A' AND 'M' includes names such as 'Adams' and 'M', but it excludes 'Miller', because 'Miller' sorts after 'M'. Whether 'adams' matches can depend on case sensitivity, which differs between databases.
The timestamp trap
Inclusive bounds cause a common bug with timestamp columns. Suppose created_at is a timestamp, and you want everything that happened in December 2022:
SELECT order_id, created_at
FROM orders
WHERE created_at BETWEEN '2022-12-01' AND '2022-12-31';A plain date literal such as '2022-12-31' is read as midnight at the start of that day (2022-12-31 00:00:00). Any order placed later on December 31 is excluded. For timestamps, use a half-open range instead:
SELECT order_id, created_at
FROM orders
WHERE created_at >= '2022-12-01'
AND created_at < '2023-01-01';This includes the start, excludes the next period's start, and has no gaps or overlaps if you chain several periods together.
IN: matching a list of values
value IN (a, b, c) is true if the value equals any item in the list. It is shorthand for a chain of OR conditions.
SELECT first_name, last_name, department
FROM employees
WHERE department IN ('Sales', 'Marketing', 'Support');This is equivalent to:
SELECT first_name, last_name, department
FROM employees
WHERE department = 'Sales'
OR department = 'Marketing'
OR department = 'Support';The IN version has an extra advantage. Because it is one condition, you do not need parentheses when you combine it with AND. The OR chain, by contrast, needs them, since AND binds more tightly than OR:
SELECT first_name, department, salary
FROM employees
WHERE department IN ('Sales', 'Marketing')
AND salary > 50000;Writing the same filter with OR and forgetting the parentheses is a classic source of wrong results. IN removes that risk.
NOT IN
NOT IN selects rows whose value is not in the list.
SELECT first_name, department
FROM employees
WHERE department NOT IN ('Sales', 'Marketing');Rows with a NULL department are not returned by this query. That is explained in the next section.
Lists of numbers and dates
IN is not limited to text. Text values need single quotes, and numbers do not.
SELECT first_name, salary
FROM employees
WHERE manager_id IN (101, 102, 105);NULL behavior with BETWEEN and IN
SQL uses three-valued logic: a condition can be true, false, or unknown. A comparison with NULL is unknown, and WHERE keeps only rows where the condition is true.
For BETWEEN, this means a row whose value is NULL is never returned, whether you write BETWEEN or NOT BETWEEN. Both are unknown for NULL. If you want rows with a missing value too, say so explicitly:
SELECT first_name, salary
FROM employees
WHERE salary BETWEEN 40000 AND 60000
OR salary IS NULL;The NOT IN trap with NULL in the list
NOT IN has a sharper problem. x NOT IN (1, 2, NULL) expands to x <> 1 AND x <> 2 AND x <> NULL. The last part is always unknown, so the whole condition can never be true. The query returns no rows at all.
This rarely happens with a hand-typed list, but it happens often with a subquery that returns a column containing NULL. For example, manager_id is NULL for employees with no manager:
SELECT first_name
FROM employees
WHERE employee_id NOT IN (SELECT manager_id FROM employees);If any manager_id is NULL, this returns nothing, even though some employees clearly manage nobody. The fix is to exclude the nulls from the subquery:
SELECT first_name
FROM employees
WHERE employee_id NOT IN (
SELECT manager_id
FROM employees
WHERE manager_id IS NOT NULL
);The plain IN form does not have this problem. A NULL in the list just never matches, and other items can still match.
Choosing between BETWEEN, IN, and comparisons
| Need | Use | Notes |
|---|---|---|
| Value within a continuous range, both ends included | `BETWEEN` | Low bound first |
| Value outside a range | `NOT BETWEEN` or `<` with `OR` and `>` | NULL rows are dropped either way |
| Value equal to one of a few known items | `IN` | Replaces a chain of `OR` |
| Value equal to none of the items | `NOT IN` | Check for NULL in the list |
| Range that excludes the upper end | `>=` and `<` | Safe for timestamps |
BETWEEN is for ranges where the order of values matters, and IN is for sets where it does not. You can use both in one query, as in the combined example below. Each condition is joined by AND, so all three must hold.
SELECT first_name, last_name
FROM employees
WHERE department IN ('Sales', 'Marketing', 'Support')
AND hire_date BETWEEN '2020-01-01' AND '2022-12-31'
AND last_name LIKE 'Mc%';Performance notes
For most databases, BETWEEN and IN can use an index on the column, just like the equivalent comparisons. A long IN list, with hundreds or thousands of values, can be slow to parse or may hit a limit on the number of items or parameters. For very large lists, load the values into a table and join to it, or use a subquery. Check your database's documentation for its limits.
Common mistakes
- Reversing the bounds in
BETWEEN, which returns no rows and no error. - Assuming
BETWEENexcludes an endpoint. Both are included. - Using
BETWEENon timestamps with a date as the upper bound. - Putting quotes around numbers in an
INlist, or leaving them off text. - Using
= (1, 2, 3)instead ofIN (1, 2, 3). The=operator compares one value to one value. - Using
NOT INagainst a list or subquery that may containNULL.
Exercise
A table orders has a timestamp column created_at. Write a query that returns every order placed in March 2023, including orders placed late on March 31. Then explain why BETWEEN '2023-03-01' AND '2023-03-31' is wrong for this task.
Show answer
Use a half-open range: SELECT order_id, created_at FROM orders WHERE created_at >= '2023-03-01' AND created_at < '2023-04-01';. The BETWEEN version is wrong because '2023-03-31' is read as 2023-03-31 00:00:00, so any order placed after midnight on March 31 is excluded.
Exercise
The query SELECT first_name FROM employees WHERE employee_id NOT IN (SELECT manager_id FROM employees); returns no rows, even though several employees manage nobody. Some employees have a NULL manager_id. Why does it return nothing, and how do you fix it?
Show answer
The subquery returns a list that contains NULL. For each employeeid, the condition expands to include `employeeid <> NULL, which is unknown, so NOT IN is never true. Fix it by filtering the subquery: WHERE manager_id IS NOT NULL` inside the subquery.