SQL ANY Operator
The ANY operator in SQL allows you to compare a value against any value in a list or subquery. It returns TRUE if at least one of the values satisfies the condition.
Syntax:
Syntax:
SELECT column_name
FROM table_name
WHERE column_name operator ANY (subquery);
- operator can be: =, !=, >, <, >=, <=
- The condition is TRUE if any one of the values in the subquery satisfies the condition
Products Table
product_id | product_name | price | category |
---|---|---|---|
1 | Laptop | 50000 | Electronics |
2 | Smartphone | 25000 | Electronics |
3 | Chair | 3000 | Furniture |
4 | Desk | 6000 | Furniture |
5 | TV | 40000 | Electronics |
Example:
Goal: List all products with a price grater than any product in the Electronics category.
SELECT product_name
FROM products
WHERE price > ANY (SELECT price FROM products WHERE category = 'Electronics');
Output:
product_name |
---|
Laptop |
TV |
Explanation:
This query compares each product's price with every price in the Electronics category.
It returns products whose price is greater than at least one price in that category.
It returns products whose price is greater than at least one price in that category.
Comparison: ANY vs ALL
Operator | Condition Type | Returns Result |
---|---|---|
ANY | At least one true | One or more comparisons are true |
ALL | Must be all true | All comparisons in the set are true |