الانتقال إلى المحتوى الرئيسي
eLearner.app
الوحدة 4 · الدرس 1 من 413/57 في الدورة~8 min
دروس الوحدة (1/4)

القوائم والنطاقات: في وبين

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 من المحاولات