Learning navigation

Code with Animation

IN, BETWEEN & LIKE

Write shorter filters with IN for lists, BETWEEN for ranges and LIKE for text patterns, and avoid the NOT IN trap.

SQL6 min readConcept 8 of 44

Three shortcuts for common tests

IN checks a value against a list. team IN ('Red', 'Green') is the same as team = 'Red' OR team = 'Green'.

BETWEEN checks a range, and it includes both ends. points BETWEEN 17 AND 24 means points >= 17 AND points <= 24.

LIKE matches text against a pattern. % stands for any run of characters, even none. _ stands for exactly one character. The pattern must match the whole text.

Shorter queries, fewer mistakes

A long chain of OR is easy to get wrong. IN says the same thing in one line. A range written with BETWEEN cannot forget one of its two ends.

LIKE is how you search text without knowing the exact value, such as every name that starts with A.

Use each one

Three queries on players, with the rows they keep:

WHERE team IN ('Red', 'Green')       -- Asha, Chen, Dara, Fay, Gus
WHERE points BETWEEN 17 AND 24        -- Ben, Dara, Fay, Hana
WHERE name LIKE '_a%'                 -- Dara, Fay, Hana

_a% means one character, then a, then anything. That is why Dara, Fay and Hana match, and Asha does not.

Put NOT in front to flip the test: NOT IN, NOT BETWEEN, NOT LIKE. In PostgreSQL, ILIKE is a case-insensitive LIKE. It is an extension, not standard SQL.

Try the shortcuts and the traps

Switch between IN, BETWEEN and LIKE, pick a condition, and read TRUE, FALSE or UNKNOWN for every player.

SELECT name, team, points
FROM players
WHERE team IN ('Red', 'Green');
players (8 rows)
nametextteamtextpointsintegerWHERE
AshaRed31TRUE
BenBlue17FALSE
ChenRedNULLTRUE
DaraGreen24TRUE
EliBlueNULLFALSE
FayRed24TRUE
GusGreen40TRUE
HanaBlue17FALSE
Result (5 rows)
nametextteamtextpointsinteger
AshaRed31
ChenRedNULL
DaraGreen24
FayRed24
GusGreen40

IN is a short way to write OR: team = 'Red' OR team = 'Green'.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Which players does `points BETWEEN 17 AND 24` keep?
  2. 2Which names does `name LIKE '_a%'` match?
  3. 3What does `WHERE points NOT IN (17, NULL)` return?

Remember this

  • IN is a short way to write a chain of OR tests on one column.
  • BETWEEN includes both ends, so a BETWEEN 17 AND 24 means a >= 17 AND a <= 24.
  • LIKE uses % for any run of characters and _ for one character, and the pattern must match the whole text.
  • NOT IN with a NULL in the list never keeps a row, so remove NULLs from the list first.

Done with this concept?

Mark it complete to track your progress. No login needed.