Careeroza
EXISTS
The SQL EXISTS Operator
EXISTS tests whether a subquery returns any row. It returns TRUE as soon as one row is found, so it stops early and is efficient.
SELECT column_name(s)
FROM table_name
WHERE EXISTS (SELECT 1 FROM ... WHERE condition);Example
Example
Employees who have handled at least one order over 300:
SELECT FirstName FROM Employees e
WHERE EXISTS (
SELECT 1 FROM Orders o
WHERE o.EmployeeID = e.EmployeeID AND o.Amount > 300
);Result: 1 row
| FirstName |
|---|
| Sara |
NOT EXISTS
Example
Employees who have handled no orders:
SELECT FirstName, Department FROM Employees e
WHERE NOT EXISTS (SELECT 1 FROM Orders o WHERE o.EmployeeID = e.EmployeeID);Result: 4 rows
| FirstName | Department |
|---|---|
| Rahul | Sales |
| Ananya | Support |
| James | Support |
| Fatima | Finance |
Note: NOT EXISTS handles NULLs correctly, while NOT IN returns nothing if the subquery contains a NULL (Orders.EmployeeID has one).