ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 4 · 4లో పాఠం 1కోర్సులో 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 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది