In SQL, ANY and ALL are operators used to compare a value with a set of values returned by a subquery. They enable more flexible filtering of query results by comparing the main query’s value with the values produced by the subquery.
SQL Any and All Syntax
SQL
x
1
SELECT column_name(s)
2
FROM table_name
3
WHERE column_name comparison_operator ANY (subquery);
4
5
SELECT column_name(s)
6
FROM table_name
7
WHERE column_name comparison_operator ALL (subquery);
SQL All With Select Syntax
SQL
1
1
SELECT column_name
2
FROM table_name
3
WHERE column_name comparison_operator ALL (SELECT column_name FROM another_table);
SQL All With WHERE and HAVING Syntax
SQL
1
1
SELECT column_name
2
FROM table_name
3
WHERE column_name > ALL (SELECT column_name FROM another_table);
4
5
SELECT column_name, COUNT(*)
6
FROM table_name
7
GROUP BY column_name
8
HAVING COUNT(*) > ALL (SELECT COUNT(*) FROM another_table);
SQL All Doctors with All Appointments After a Certain Date Example
This query checks if all appointments for a doctor occur after the given date. The subquery retrieves doctor_id with future appointments, and the ALL operator ensures that all appointments for each doctor are after that date.
SQL
1
1
SELECT d.first_name, d.last_name
2
FROM Doctors d
3
WHERE d.doctor_id = ALL (
4
SELECT a.doctor_id
5
FROM Appointments a
6
WHERE a.appointment_date > '2024-01-01'
7
);