Skip to content

Conditional expressions: ANY/ALL, BETWEEN, EXISTS, IN, IS NULL, LIKE and CASE

View as Markdown

Conditional expressions are the building blocks of WHERE, HAVING and ON clauses. Each one returns true, false or unknown (NULL); a row passes a condition only when it is true. The simple comparisons (=, <>, < and so on) are described in Comparison operators.

expression comparison_operator {ANY | SOME | ALL} {(subquery) | {value, ...} | collection_column}
  • ANY and SOME (synonyms): true if the comparison is true for at least one value on the right.
  • ALL: true if the comparison is true for every value on the right.
  • The values can come from a subquery, a list in braces, or a collection column.

= ANY is the same as IN:

SELECT code, name FROM countries WHERE code = ANY {'FRA', 'DEU', 'ITA'} ORDER BY code;
code name
DEU Germany
FRA France
ITA Italy

Products more expensive than every Lando product:

SELECT id, name, unit_price FROM product
WHERE unit_price > ALL (SELECT unit_price FROM product WHERE name LIKE 'Lando%')
ORDER BY unit_price DESC;
id name unit_price
38 Côte de Blaye 263.50
29 Thüringer Rostbratwurst 123.79

A NULL among the values matters: x > ALL {50, 100, NULL} is never true (it is false or unknown), while x > ANY {100, 200, NULL} is true when x exceeds one of the other values. Against the product table the first finds 0 rows and the second 2.

expression [NOT] BETWEEN low AND high

True if expression is greater than or equal to low and less than or equal to high: x BETWEEN a AND b is the same as x >= a AND x <= b. It works for numbers, strings, and dates and times.

SELECT id, name, unit_price FROM product WHERE unit_price BETWEEN 120 AND 300 ORDER BY id;
id name unit_price
29 Thüringer Rostbratwurst 123.79
38 Côte de Blaye 263.50

For strings, mind the upper bound: name BETWEEN 'S' AND 'T' includes names starting with S but not those starting with T (except 'T' itself), because 'Thailand' is greater than 'T':

SELECT code, name FROM countries WHERE name BETWEEN 'S' AND 'T' ORDER BY code;
code name
CHE Switzerland
ESP Spain
SGP Singapore
SWE Sweden
[NOT] EXISTS (subquery)

True if the subquery returns at least one row. The subquery's select list does not matter. EXISTS is often correlated with the outer query. The number of customers who never ordered:

SELECT COUNT(*) FROM customer c
WHERE NOT EXISTS (SELECT * FROM orders o WHERE o.customer_id = c.id);
count(*)
350
expression [NOT] IN {(subquery) | (value, ...) | {value, ...}}

True if expression equals one of the values. x IN (a, b) is the same as x = ANY {a, b}.

SELECT code, name FROM countries WHERE code IN ('FRA', 'DEU', 'ITA') ORDER BY code;
code name
DEU Germany
FRA France
ITA Italy

NOT IN returns the other 22 countries. If the list contains NULL, however, NOT IN is never true: code NOT IN ('FRA', NULL) matches no row, because comparing with NULL is unknown. Make sure a subquery used with NOT IN cannot return NULL, or use NOT EXISTS.

expression IS [NOT] NULL

True if expression is (not) NULL. Always use IS NULL to test for NULL: shipped_date = NULL is unknown for every row and selects nothing, while shipped_date IS NULL finds the nine unshipped orders.

SELECT COUNT(*) FROM orders WHERE shipped_date IS NULL;
count(*)
9
expression [NOT] LIKE pattern [ESCAPE escape_char]

Matches a string against a pattern:

  • % matches any sequence of characters, including none.
  • _ matches exactly one character.
  • ESCAPE escape_char: a character that makes the next % or _ in the pattern match itself.

LIKE works on CHAR and VARCHAR values; whether it is case-sensitive depends on the collation (with the default utf8_bin, it is). Use UPPER or LOWER on both sides for a case-insensitive match, or a function-based index to make that fast.

SELECT name FROM brand WHERE name LIKE '____' ORDER BY name;
name
Fila
Head
Hoka
Keen
Nike
Puma
Vans
Zara
SELECT name FROM brand WHERE UPPER(name) LIKE '%A_O%' ORDER BY name;
name
Alo Yoga
Babolat
Billabong
Diadora
Lacoste
Patagonia
Salomon

To find a literal %, escape it:

SELECT 'Save 10% today' LIKE '%10!%%' ESCAPE '!', 'Save 10 today' LIKE '%10!%%' ESCAPE '!' FROM db_root;
'Save 10% today' like '%10!%%' escape '!' 'Save 10 today' like '%10!%%' escape '!'
1 0

Whether a backslash acts as an escape character without an ESCAPE clause depends on the no_backslash_escapes and require_like_escape_character parameters. For more powerful patterns, see Regular expressions.

CASE expression
WHEN value THEN result
[WHEN value THEN result ...]
[ELSE result]
END
CASE
WHEN condition THEN result
[WHEN condition THEN result ...]
[ELSE result]
END

The first form compares expression with each value; the second evaluates each condition. The result of the first WHEN that matches is returned, or the ELSE result, or NULL if there is no ELSE.

SELECT product_id, discount_pct,
CASE discount_pct WHEN 0 THEN 'full price' WHEN 25 THEN 'quarter off' ELSE 'discounted' END AS pricing
FROM order_items
WHERE order_id = 455
ORDER BY product_id;
product_id discount_pct pricing
123 0 full price
335 0 full price
1795 25 quarter off
SELECT id, unit_price,
CASE WHEN unit_price >= 100 THEN 'premium'
WHEN unit_price >= 30 THEN 'standard'
ELSE 'budget'
END AS tier
FROM product
WHERE id IN (29, 123, 335, 1795)
ORDER BY id;
id unit_price tier
29 123.79 premium
123 45.00 standard
335 20.00 budget
1795 29.00 budget

All results must have the same type or a common type. If one result is a variable-length string, the result is a variable-length string; if the results are numbers of different types, the result keeps all their decimal places. The functions DECODE, IF and NVL are shorter forms of common CASE expressions.