SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL GROUP BY SQL Having SQL In SQL INSERT INTO SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL ORDER BY SQL Select SQL Select Into SQL Top Limit Fetch SQL Stored Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL Backup Database SQL Check SQL Constraints SQL Create View SQL Create Database SQL Create Table SQL Data types SQL Dates SQL Default Constraint SQL Drop Database SQL Drop Table SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL ANY and ALL

ANY and ALL compare a value with the result of a subquery. They are useful when a condition depends on a set of values instead of one fixed value.

Syntax

SELECT column_name
FROM table_name
WHERE column_name operator ANY (subquery);
SELECT column_name
FROM table_name
WHERE column_name operator ALL (subquery);

ANY is true when the comparison matches at least one value from the subquery. ALL is true only when the comparison matches every value from the subquery.

Example with ANY

Find products that are more expensive than at least one product in category 2:

SELECT product_name, price
FROM products
WHERE price > ANY (
    SELECT price
    FROM products
    WHERE category_id = 2
);

Example with ALL

Find products that are more expensive than every product in category 2:

SELECT product_name, price
FROM products
WHERE price > ALL (
    SELECT price
    FROM products
    WHERE category_id = 2
);

The second query is stricter. ANY asks for one match. ALL asks the database to be impressed by the entire list.

Common mistakes

Related topics

Review SQL EXISTS, SQL IN, SQL Operators and the SQL Formatter.