The ANY and ALL operators are used with a WHERE or HAVING clause. They allow you to perform a comparison between a single column value and a range of other values.
ANY OperatorThe ANY operator:
TRUE if any of the subquery values meet the conditionANY SyntaxSELECT column_name(s)
FROM table_name
WHERE column_name operator ANY (SELECT column_name FROM table_name WHERE condition);
Note: The
operatormust be a standard comparison operator (=,<,>,<=,>=,<>).
ALL OperatorThe ALL operator:
TRUE if all of the subquery values meet the conditionALL SyntaxSELECT column_name(s)
FROM table_name
WHERE column_name operator ALL (SELECT column_name FROM table_name WHERE condition);
Below is a selection from the Customers table:
| Customers Table: |
| CustomerID | CustomerName | Country |
|---|---|---|
| 1 | Alfreds Futterkiste | Germany |
| 2 | Ana Trujillo Emparedados | Mexico |
| 3 | Antonio Moreno Taquería | Mexico |
| 4 | Around the Horn | UK |
| 5 | Berglunds snabbköp | Sweden |
ANY ExampleThe following SQL statement lists the CustomerName if it finds that the country is ANY of the countries returned by the subquery.
SELECT CustomerName FROM Customers WHERE Country = ANY (SELECT Country FROM Customers WHERE Country = 'Mexico');
This would return "Ana Trujillo Emparedados" and "Antonio Moreno Taquería", as their country matches the subquery result.
ALL ExampleThe following SQL statement lists CustomerName if the country is alphabetically greater than ALL countries returned by the subquery. This is a much stricter condition.
SELECT CustomerName FROM Customers WHERE Country > ALL (SELECT Country FROM Customers WHERE Country = 'Germany' OR Country = 'Mexico');
This query would return customers from "Sweden" and "UK", as these country names are alphabetically after both "Germany" and "Mexico".