Sub topic 8
Ranges and Lists with `BETWEEN` and `IN`
Assume you know the basics of tables, rows, columns, SELECT, FROM, and WHERE. This chapter uses an employees table with columns such as first_name, last_name, department, salary, and hire_date.
Testing an inclusive range with `BETWEEN`
BETWEEN tests whether a value falls within a range. The boundary values are included.
SELECT first_name, last_name, salary
FROM employees
WHERE salary BETWEEN 40000 AND 60000;This returns employees whose salary is at least 40,000 and at most 60,000. It is equivalent to:
SELECT first_name, last_name, salary
FROM employees
WHERE salary >= 40000
AND salary <= 60000;The lower and upper bounds must be written in the correct order. BETWEEN 60000 AND 40000 normally matches no rows.
You can use BETWEEN with dates as well:
SELECT first_name, hire_date
FROM employees
WHERE hire_date BETWEEN '2020-01-01' AND '2022-12-31';For a date column, this asks for dates from January 1, 2020 through December 31, 2022, including both dates.
Matching one of several values with `IN`
IN tests whether a value equals one item in a list. It is shorter and clearer than several OR conditions.
SELECT first_name, last_name
FROM employees
WHERE department IN ('Sales', 'Marketing', 'Support');This is equivalent to:
SELECT first_name, last_name
FROM employees
WHERE department = 'Sales'
OR department = 'Marketing'
OR department = 'Support';Text values need single quotes. Numbers do not:
SELECT first_name, salary
FROM employees
WHERE salary IN (45000, 50000, 55000);Use NOT IN when you want to exclude the listed values:
SELECT first_name, department
FROM employees
WHERE department NOT IN ('Sales', 'Marketing');IN can also use the result of a subquery, which is a query inside another query. That form is useful when the allowed list comes from another table, but a literal list is enough for this chapter.
Combining ranges and lists
Conditions can be combined with AND:
SELECT first_name, last_name, department, salary
FROM employees
WHERE department IN ('Sales', 'Marketing', 'Support')
AND hire_date BETWEEN '2020-01-01' AND '2022-12-31'
AND salary >= 50000;A row must satisfy every condition. The query first describes the allowed departments, then the allowed hiring period, then the minimum salary.
| Operator | Meaning | Example |
|---|---|---|
| `BETWEEN` | Inclusive range | `salary BETWEEN 40000 AND 60000` |
| `IN` | Matches one listed value | `department IN ('Sales', 'Support')` |
| `NOT IN` | Matches none of the listed values | `department NOT IN ('Sales')` |
Exercise
Write a query that returns the first and last names of employees in either the Engineering or Support department whose salary is between 60000 and 90000, inclusive.
Show answer
SELECT firstname, lastname FROM employees WHERE department IN ('Engineering', 'Support') AND salary BETWEEN 60000 AND 90000;