Skip to main content
eLearner.app
Module 4 · Lesson 1 of 413/57 in the course~8 min
Module lessons (1/4)

Lists and ranges: IN and BETWEEN

In the previous modules you filtered with WHERE using equalities and comparisons: salary > 30000, department_id = 1, hired_on >= '2020-01-01'. But when the condition becomes "the value must be one of these five", chained ORs pile up:

SQL
-- Heavy and fragile: adding a department means touching the query
SELECT first_name, last_name
FROM   employees
WHERE  department_id = 1
   OR  department_id = 2
   OR  department_id = 3;

SQL offers two shortcuts to make this readable.

IN — "one of these"

The IN (...) operator takes a list of values and returns true if the column equals any of them:

SQL
SELECT first_name, last_name, department_id
FROM   employees
WHERE  department_id IN (1, 2, 3);

It is semantically identical to the ORs above, but far more readable: it reads naturally as "where department_id is in (1, 2, 3)". It also works with strings and dates:

SQL
SELECT name
FROM   departments
WHERE  city IN ('Milano', 'Roma');

There is also NOT IN (...), which does the opposite:

SQL
-- Employees who are NOT in Engineering or Sales:
SELECT first_name, last_name
FROM   employees
WHERE  department_id NOT IN (1, 2);

BETWEEN — "between A and B, both inclusive"

When the condition is a continuous range (numbers, dates), instead of writing column >= A AND column <= B you have BETWEEN A AND B:

SQL
-- Employees with a salary between 30000 and 50000 (both inclusive):
SELECT first_name, last_name, salary
FROM   employees
WHERE  salary BETWEEN 30000 AND 50000;

BETWEEN is inclusive on both endpoints. It works very nicely with dates too:

SQL
-- Everyone hired in 2020:
SELECT first_name, last_name, hired_on
FROM   employees
WHERE  hired_on BETWEEN '2020-01-01' AND '2020-12-31';

Try it

Exercise#sql.m4.l1.e1
Attempts: 0Loading…

Show first name (first_name), last name (last_name) and salary (salary) of employees with a salary between 30000 and 50000 inclusive. Three columns.

Loading editor…
Show hint

Use BETWEEN 30000 AND 50000 — more compact and readable than two comparisons joined by AND.

Solution available after 3 attempts

Review exercise

Exercise#sql.m4.l1.e2
Attempts: 0Loading…

List first name (first_name) and last name (last_name) of employees working in departments 1, 2 or 4 (use IN). Order alphabetically by last name.

Loading editor…
Show hint

WHERE department_id IN (1, 2, 4) is the compact version of three ORs.

Solution available after 3 attempts