;

SQL ANY & ALL


In this tutorial, we will learn how to use ANY and ALL operator using SQL.

SQL ANY and ALL Operators

  • SQL ANY and ALL Operators are used with a WHERE or HAVING Clause.
  • SQL ANY operator returns true if any of the subquery values satisfy the given condition.
  • SQL ALL operator returns true if ALL of the subquery values satisfy the given condition.
  • Both ANY and ALL operators must be preceded by the comparison operators such as ( =, <>, !=, >, >=, <, or <=).
  • Both ANY and ALL operator supported by following DBMS such as MySQL, PostgreSQL, SQL Server, Oracle.
Syntax - ANY Operator
SELECT column(s)
FROM tableName
WHERE column operator ANY
(SELECT column FROM tableName WHERE CONDITION);
Syntax - ALL Operator 
SELECT column(s)
FROM tableName
WHERE column operator ALL
(SELECT column FROM tableName WHERE CONDITION);

Example:

Let us consider this table "Employee" for records.

Table Name: Employee

ID EmpName City Country Gender Salary
1 Shankar Delhi India male 25000
2 Sourabh Delhi India male 30000
3 Ranvijay Mumbai India male 15000
4 Kapil Noida India male 25000
5 Shalini Jaipur India female 18000
6 Rakesh Faridabad India male 23000
7 Akshay Mumbai India male 21000
8 Sarah New York US female 76000
9 Rocky Noida India male 28000

Example of ANY Operator

For finding ANY employee salary less than 25000 using ANY operator, a query will be:

Example - ANY Operator
SELECT EmpName,Salary 
FROM Employee
WHERE Salary = ANY(SELECT Salary FROM Employee WHERE Salary < 25000);
Output
EmpName Salary
Ranvijay 15000
Shalini 18000
Rakesh 23000
Akshay 21000

Example of ALL Operator

For finding employee salary equals to 25000 using ALL operator, a query will be:

Example - ALL Operator
SELECT EmpName,Salary 
FROM Employee
WHERE Salary = ALL(SELECT Salary FROM Employee WHERE Salary = 25000);
Output
EmpName Salary
Shankar 25000
Kapil 25000