Sub topic 7
Filtering ranges with BETWEEN
This chapter covers how BETWEEN tests whether a value falls inside a range, where its edges sit, and what goes wrong at those edges. It assumes you can write a basic SELECT, know what tables, rows, and columns are, and can use comparison operators (=, <, >=) and AND/OR in a WHERE clause. Date and timestamp ranges get their own chapter. Here we focus on the predicate itself, using numbers and text.
What BETWEEN does
BETWEEN is a predicate, an expression in a WHERE clause that evaluates to true, false, or unknown. It keeps a row when a value lies between a lower and an upper bound, including both bounds.
SELECT id, name, salary
FROM employees
WHERE salary BETWEEN 50000 AND 70000;This is the same as writing two comparisons:
SELECT id, name, salary
FROM employees
WHERE salary >= 50000
AND salary <= 70000;A salary of exactly 50000 or exactly 70000 passes. The general form is:
value BETWEEN low AND highThe lower bound must come first. BETWEEN is a shorthand, and it adds no new capability. Its benefit is readability: the column name appears once, and the range reads as one idea.
A table to experiment with
The examples below use this small table. You can run them in PostgreSQL, MySQL, SQLite, or SQL Server.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50),
department VARCHAR(30),
salary INTEGER
);
INSERT INTO employees (id, name, department, salary) VALUES
(1, 'Ana', 'Sales', 50000),
(2, 'Ben', 'Support', 62000),
(3, 'Chloe', 'Sales', 70000),
(4, 'Dev', 'Marketing', 70001),
(5, 'Eli', 'Support', 49999),
(6, 'Fay', 'Sales', NULL);Running the first query on this data returns Ana (50000), Ben (62000), and Chloe (70000). Dev is one unit above the upper bound, and Eli is one unit below the lower bound. Fay is also missing, and the reason is covered below.
Both bounds are included
Because BETWEEN is inclusive, BETWEEN 1 AND 10 includes 1 and 10. This is the first thing to check when a count looks off by a row or two. If you need to exclude one end, BETWEEN can't express it, so write the comparisons yourself:
SELECT id, name, salary
FROM employees
WHERE salary >= 50000
AND salary < 70000;This keeps 50000 and drops 70000. A range that includes its lower end and excludes its upper end is called half-open. It matters a lot for dates, and the next chapter returns to it.
The lower bound must come first
BETWEEN does not sort its bounds for you. If the first bound is larger than the second, no value can satisfy both comparisons, so the result is empty.
SELECT id, name, salary
FROM employees
WHERE salary BETWEEN 70000 AND 50000;This returns no rows and raises no error. It is a common source of silent bugs, especially when the bounds come from application parameters or from user input such as "from" and "to" fields. If the two values might arrive in either order, normalize them in your application first.
PostgreSQL offers BETWEEN SYMMETRIC, which swaps the bounds when needed. It is not available in most other databases, so don't rely on it if your code must be portable.
BETWEEN with decimals
BETWEEN works with any type that has an ordering, including decimals. The inclusive upper bound can still surprise you with fractional values:
-- Does "up to 70000" include 70000.50?
SELECT id, salary
FROM employees
WHERE salary BETWEEN 50000 AND 70000;If salary were a DECIMAL(10,2) column, a row with 70000.50 would be excluded, because it is greater than 70000. People sometimes patch this by writing BETWEEN 50000 AND 70000.99. That fails for 70000.995 and breaks if the column's precision changes. A half-open range is safer because it makes no assumption about precision:
SELECT id, salary
FROM employees
WHERE salary >= 50000
AND salary < 70001;For integers this works cleanly. For decimals, choose a bound that is the next meaningful boundary (for example, the start of the next pay band) and use <.
BETWEEN with text
Text values have an order too, so BETWEEN works on strings:
SELECT id, name
FROM employees
WHERE name BETWEEN 'A' AND 'D';Here the comparison depends on the database's collation, the rule that defines how strings are ordered and compared. Two consequences follow:
'Dev'is greater than'D', because a longer string with the same start sorts after the shorter one. Soname BETWEEN 'A' AND 'D'excludes Dev, but includes a name that is exactly'D'. People often expect "names starting with A through D", which this does not give them.- Case and accent handling vary. In a case-sensitive collation, lowercase letters may sort after all uppercase letters, so
'ana'may fall outsideBETWEEN 'A' AND 'D'.
To include every name starting with D, move the upper bound past the whole letter:
SELECT id, name
FROM employees
WHERE name >= 'A'
AND name < 'E';For anything that depends on prefixes, LIKE (covered earlier in this tutorial) is often clearer. For ranges of letters, the half-open form above is the most dependable choice.
Bounds can be expressions or columns
The bounds don't have to be literals. They can be arithmetic, parameters, subqueries that return one value, or other columns:
SELECT id, name, salary
FROM employees
WHERE salary BETWEEN 40000 * 1.25 AND 40000 * 1.75;A bound can also come from another column in the same row. This is useful for rows that carry their own limits:
SELECT id, name
FROM employees e
JOIN salary_bands b ON e.department = b.department
WHERE e.salary BETWEEN b.min_salary AND b.max_salary;Here salary_bands is a table with one row per department and the columns department, min_salary, and max_salary. Each employee is compared with the limits for their own department.
NULL and BETWEEN
In SQL, NULL means "no known value". Any comparison with NULL gives unknown, not true or false, and a WHERE clause keeps only rows where the predicate is true. In the sample data, Fay has a NULL salary:
NULL >= 50000is unknown.NULL <= 70000is unknown.- So
NULL BETWEEN 50000 AND 70000is unknown, and Fay's row is not returned.
The same applies if a bound is NULL. salary BETWEEN 50000 AND NULL can never be true. If the value is already above 50000, the upper test is unknown, so the combined result is unknown. If the value is below 50000, the lower test is false, so the result is false. A query with a NULL bound therefore returns nothing, and a bug in your parameter handling can hide behind that empty result.
If you want rows with a missing value to appear in the output, you have to ask for them:
SELECT id, name, salary
FROM employees
WHERE salary BETWEEN 50000 AND 70000
OR salary IS NULL;Use IS NULL for this test. salary = NULL is always unknown and never matches. The next chapters cover three-valued logic in more detail, including how it affects negated predicates.
NOT BETWEEN, briefly
NOT BETWEEN is the opposite test: it keeps values outside the range.
SELECT id, name, salary
FROM employees
WHERE salary NOT BETWEEN 50000 AND 70000;This returns Dev (70001) and Eli (49999). It is equivalent to salary < 50000 OR salary > 70000. Fay is still excluded: negating an unknown result gives unknown, not true. A later chapter covers negation in full.
Combining BETWEEN with AND and OR
BETWEEN ... AND ... uses the word AND as part of its own syntax. The database knows that the first AND after BETWEEN belongs to the range, so this query is valid and unambiguous:
SELECT id, name, department, salary
FROM employees
WHERE salary BETWEEN 50000 AND 70000
AND department = 'Sales';The first AND pairs the two bounds. The second one joins the two predicates. With OR, use parentheses to state what you mean, since AND binds more tightly than OR:
SELECT id, name, department, salary
FROM employees
WHERE department = 'Sales'
OR department = 'Support'
AND salary BETWEEN 60000 AND 70000;Because AND is evaluated first, this means "Sales employees at any salary, or Support employees paid 60000–70000". If you meant to apply the salary range to both departments, write:
SELECT id, name, department, salary
FROM employees
WHERE (department = 'Sales' OR department = 'Support')
AND salary BETWEEN 60000 AND 70000;BETWEEN and indexes
A B-tree index keeps values in sorted order, so a range predicate on an indexed column can usually be answered by finding the lower bound and reading forward until the upper bound. That is why BETWEEN on a plain, indexed column is typically efficient.
This benefit disappears if you apply a function or calculation to the column:
-- Can typically use an index on salary:
WHERE salary BETWEEN 50000 AND 70000
-- Typically cannot use a plain index on salary:
WHERE salary / 12 BETWEEN 4000 AND 6000Put the calculation on the constant side instead: salary BETWEEN 4000 * 12 AND 6000 * 12. The optimizer may still choose a full scan if the range covers a large share of the table, and behavior differs across databases, so check the query plan (EXPLAIN) for real workloads.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Reversed bounds (`BETWEEN 70000 AND 50000`) | Empty result, no error | Put the lower value first |
| Expecting the upper bound to be excluded | One extra row at the edge | Use `>=` and `<` for a half-open range |
| Using `BETWEEN` with decimals and an integer upper bound | Values just above the bound are dropped | Use `<` with the next boundary |
| Using `BETWEEN 'A' AND 'D'` to mean "starts with A–D" | Excludes names such as `'Dev'` | Use `name >= 'A' AND name < 'E'` |
| Forgetting `NULL` values | Rows with missing values vanish | Add `OR column IS NULL` if they should stay |
| Mixing `OR` with `BETWEEN` without parentheses | Range applies to only part of the logic | Group the `OR` terms in parentheses |
Exercises
Exercise
Using the sample employees table, what does SELECT id FROM employees WHERE salary BETWEEN 49999 AND 62000; return? Which rows are excluded and why?
Show answer
It returns ids 1, 2, and 5. Eli (49999) and Ben (62000) sit exactly on the bounds and are included, and Ana (50000) falls inside. Chloe (70000) and Dev (70001) are above 62000. Fay (id 6) has a NULL salary, so the predicate is unknown and her row is not returned.
Exercise
A report must list employees paid from 50000 up to, but not including, 70000, and must also list employees whose salary is missing. Write the WHERE clause, and explain why BETWEEN is the wrong tool for the first part.
Show answer
WHERE (salary >= 50000 AND salary < 70000) OR salary IS NULL. BETWEEN always includes its upper bound, so it would also return employees paid exactly 70000. The parentheses keep the range test together, and IS NULL is needed because a comparison with NULL is unknown and never true.
Exercise
A query uses WHERE department = 'Sales' OR department = 'Support' AND salary BETWEEN 60000 AND 70000. Which rows does it return from the sample data, and how would you apply the salary range to both departments?
Show answer
AND is evaluated before OR, so it returns every Sales employee (Ana, Chloe, Fay) plus Support employees paid 60000–70000 (Ben). To apply the range to both departments, write WHERE (department = 'Sales' OR department = 'Support') AND salary BETWEEN 60000 AND 70000. That returns Chloe and Ben.