đ SQL Tutorial: EXISTS, NOT EXISTS, ANY, and ALL
These SQL operators are useful for checking existence and comparing values from subqueries.
đ Sample Tables
employees
employee_id | name | department_id | salary |
---|---|---|---|
1 | Arif | 101 | 50000 |
2 | Nasrin | 102 | 60000 |
3 | Rafi | 101 | 55000 |
4 | Ritu | 103 | 45000 |
5 | Faruk | 102 | 62000 |
departments
department_id | department_name |
---|---|
101 | Human Resources |
102 | Engineering |
103 | Marketing |
104 | Finance |
1️⃣ EXISTS
Find departments which have at least one employee.
SELECT department_name
FROM departments d
WHERE EXISTS (
SELECT 1 FROM employees e WHERE e.department_id = d.department_id
);
Output:
department_name |
---|
Human Resources |
Engineering |
Marketing |
2️⃣ NOT EXISTS
Find departments which have no employees.
SELECT department_name
FROM departments d
WHERE NOT EXISTS (
SELECT 1 FROM employees e WHERE e.department_id = d.department_id
);
Output:
department_name |
---|
Finance |
3️⃣ ANY
Find employees whose salary is greater than any employee in department 101.
SELECT name, salary
FROM employees
WHERE salary > ANY (
SELECT salary FROM employees WHERE department_id = 101
);
Output:
name | salary |
---|---|
Nasrin | 60000 |
Faruk | 62000 |
4️⃣ ALL
Find employees whose salary is greater than all employees in department 101.
SELECT name, salary
FROM employees
WHERE salary > ALL (
SELECT salary FROM employees WHERE department_id = 101
);
Output:
name | salary |
---|---|
Faruk | 62000 |
đ Summary:
- EXISTS: Checks if subquery returns any rows.
- NOT EXISTS: Checks if subquery returns no rows.
- ANY: True if condition holds for any value in subquery.
- ALL: True if condition holds for all values in subquery.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ