![]() |
VOOZH | about |
In SQL, the ALL and ANY operators are used to compare a value against a set of values returned by a subquery. They help filter results based on conditions evaluated over multiple values.
The SQL ALL operator compares a value to every value returned by a subquery. A condition using ALL is TRUE only if it holds for all values in the subquery result.
Example: First, we will create a demo SQL database and table, on which we will use the ALL command.
Query:
SELECT * FROM Products
WHERE Price > ALL (SELECT Price FROM Products WHERE Price < 500);
Output:
👁 Screenshot-2026-05-25-122859Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name comparison_operator ALL
(SELECT column_name
FROM table_name
WHERE condition(s));
The ALL operator can be used in conjunction with SELECT, WHERE and HAVING statements to refine your data filtering.
Query:
SELECT ALL ProductName
FROM Products
WHERE TRUE;
Output:
This query retrieves all product names from the Products table because TRUE always evaluates as true for every row.
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID
FROM OrderDetails
WHERE Quantity = 6 OR Quantity = 2);
Output:
This query ensures that the product names returned have ALL quantities of 6 or 2 in the OrderDetails table.
SELECT OrderID
FROM OrderDetails
GROUP BY OrderID
HAVING MAX(Quantity) > ALL (SELECT AVG(Quantity)
FROM OrderDetails
GROUP BY OrderID);
Output:
This query filters out OrderIDs where the maximum quantity is greater than the average quantity of the orders.
The SQL ANY operator compares a value with the values returned by a subquery and evaluates to TRUE if at least one value satisfies the given condition.
=, >, <, >=, <= or <>.Example: First, we will create a demo SQL database and table, on which we will use the ANY command.
Query:
SELECT * FROM Products
WHERE Price < ANY (SELECT Price FROM Products WHERE Price > 500);
Output:
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name comparison_operator ANY
(SELECT column_name
FROM table_name
WHERE condition(s));
The ANY operator can be used with SELECT, WHERE and HAVING clauses to filter data by matching a condition against any value in a subquery result.
Query:
SELECT DISTINCT CategoryID
FROM Products
WHERE ProductID = ANY (SELECT ProductID
FROM OrderDetails);
Output:
This query finds the distinct CategoryIDs of products that exist in the OrderDetails table.
Query:
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID
FROM OrderDetails
WHERE Quantity = 9);
Output:
This query retrieves product names where at least one record in the OrderDetails table has a quantity of 9.
To better understand SQL comparison operators, see our detailed comparison of ANY vs ALL in SQL