メインコンテンツにスキップ
eLearner.app
モジュール 4 · レッスン 1 / 4コース内の 13/57~8 min
モジュールのレッスン (1/4)

リストと範囲: IN と 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

運動#sql.m4.l1.e1
試行回数: 0読み込み中…

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

エディターを読み込み中…
ヒントを表示

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

3 回の試行後に解決策が利用可能になります

Review exercise

運動#sql.m4.l1.e2
試行回数: 0読み込み中…

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.

エディターを読み込み中…
ヒントを表示

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

3 回の試行後に解決策が利用可能になります