IN, BETWEEN & LIKE
Write shorter filters with IN for lists, BETWEEN for ranges and LIKE for text patterns, and avoid the NOT IN trap.
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.
| nametext | teamtext | pointsinteger | WHERE |
|---|---|---|---|
| Asha | Red | 31 | TRUE |
| Ben | Blue | 17 | FALSE |
| Chen | Red | NULL | TRUE |
| Dara | Green | 24 | TRUE |
| Eli | Blue | NULL | FALSE |
| Fay | Red | 24 | TRUE |
| Gus | Green | 40 | TRUE |
| Hana | Blue | 17 | FALSE |
| nametext | teamtext | pointsinteger |
|---|---|---|
| Asha | Red | 31 |
| Chen | Red | NULL |
| Dara | Green | 24 |
| Fay | Red | 24 |
| Gus | Green | 40 |
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.
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.