IN, BETWEEN, LIKE and NULL
048 min
You can do a lot with = and >, but SQL has four more tools that make conditions short and precise.
IN — one of a list
Instead of several ORs:
This is the same as city = 'Buxoro' OR city = 'Navoiy' OR city = 'Urganch', just shorter. The opposite is NOT IN.
BETWEEN — within a range
BETWEEN a AND b includes both ends, so it means >= a AND <= b. It works for dates too:
LIKE — matching a pattern
%— any number of characters (including none);_— exactly one character.
| Pattern | Meaning |
|---|---|
'A%' |
starts with A |
'%ova' |
ends with “ova” |
'%bek%' |
contains “bek” |
'_a%' |
second letter is “a” |
In PostgreSQL LIKE is case-sensitive: 'a%' will not find “Aziz”. For a case-insensitive search there is ILIKE: WHERE first_name ILIKE 'a%'.
NULL — no value
NULL means “unknown” or “not filled in”. For example, some students have no phone number on record. NULL equals nothing — not even itself! That is why = NULL does not work:
The right way is IS NULL and IS NOT NULL.
From the products table, show name and brand of the products made by “Apple”, “Samsung” or “Xiaomi”.
Show name and price of the products priced from 1,000,000 to 3,000,000 inclusive.
Show first_name and phone of the customers who have no e-mail on record.
Remember
IN (…)— one of a list;BETWEEN a AND b— a range including both ends.LIKE:%— any characters,_— one character.- Only
IS NULL/IS NOT NULLwork withNULL.