EXISTS and NOT EXISTS
Description
The EXISTS
and NOT EXISTS
operators in SQL are used to test for the existence or non-existence of rows in a subquery. They are typically used in WHERE
clauses to filter rows based on whether a subquery returns any results.
EXISTS
Operator
EXISTS
OperatorThe EXISTS
operator returns TRUE
if the subquery returns one or more rows. It is commonly used to check for the presence of related data.
Syntax:
Example:
Consider two tables, employees
and departments
:
employees:
1
Alice
101
2
Bob
102
3
Charlie
103
4
Dave
104
5
Eve
105
departments:
101
Sales
102
Engineering
103
HR
To find employees who belong to a department listed in the departments
table:
Result:
Alice
Bob
Charlie
NOT EXISTS
Operator
NOT EXISTS
OperatorThe NOT EXISTS
operator returns TRUE
if the subquery returns no rows. It is used to check for the absence of related data.
Syntax:
Example:
To find employees who do not belong to any department listed in the departments
table:
Result:
Dave
Eve
Last updated
Was this helpful?