Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

SQL | ALL and ANY

ALL & ANY are logical operators in SQL. They return boolean value as a result.

ALL

The ALL operator returns TRUE iff all of the subqueries values meet the condition.
The ALL must be preceded by comparison operators and evaluates true if all of
the subqueries values meet the condition.

ALL is used with SELECT, WHERE, HAVING statement.

Syntax:

SELECT column_name(s)

FROM table_name

WHERE column_name comparison_operator ALL (SELECT column_name

FROM table_name WHERE condition(s));

Example:
Consider the following Products Table and OrderDetails Table,

Products Table
OrderDetails Table

Find the OrderID whose maximum Quantity among all product of that OrderID is
greater than average quantity of all OrderID.

SELECT OrderID

FROM OrderDetails

GROUP BY OrderID

HAVING max(Quantity) > ALL (SELECT avg(Quantity)

FROM OrderDetails

GROUP BY OrderID);

Output:
ANY

ANY compares a value to each value in a list or results from a query and evaluates
to true if the result of an inner query contains at least one row.

 ANY return true if any of the subqueries values meet the condition.

 ANY must be preceded by comparison operators.

Syntax:

SELECT column_name(s)

FROM table_name

WHERE column_name comparison_operator ANY (SELECT column_name

FROM table_name

WHERE condition(s));

Queries

Find the Distinct CategoryID of the products which have any record in
OrderDetails Table.

SELECT DISTINCT CategoryID

FROM Products

WHERE ProductID = ANY (SELECT ProductID

FROM OrderDetails);

Output:
EXISTS and NOT EXISTS:
 The keywords EXISTS and NOT EXISTS are designed for use only with
subqueries.
 They produce a simple true/false result.

 EXISTS is true if and only if there exists at least one row in the result table
returned by the subquery; it is false if the subquery returns an empty result
table.

 NOT EXISTS is the opposite of EXISTS.

 NOT EXISTS check only for the nonexistence of rows in the subquery result
table, the subquery can contain any number of columns.

Example: Query using EXISTS

Find all staff who work in a London branch office.

SELECT staffNo, fName, IName, position


FROM Staff s
WHERE EXISTS (SELECT * FROM Branch b
WHERE s.branchNo = b.branchNoANDcity = ‘London’);

The result table is shown in Table

staffNo fName IName position


SL21 John White Manager
SL41 Julie Lee Assistant

Multi table queries:


Refer join operations in unit 1

Combining result tables:


Refer set operations in unit 1

You might also like