The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns true if the subquery returns one or more records. Otherwise, it returns false.
EXISTS SyntaxSELECT column_name(s) FROM table_name WHERE EXISTS (SELECT column_name FROM table_name WHERE condition);
Customers Table:
| CustomerID | CustomerName |
|---|---|
| 1 | Alfreds Futterkiste |
| 2 | Ana Trujillo Emparedados |
| 4 | Around the Horn |
Orders Table:
| OrderID | CustomerID |
|---|---|
| 10308 | 2 |
| 10310 | 1 |
EXISTS ExampleThe EXISTS operator can be more efficient than a JOIN or IN clause for checking existence, because it can stop processing the subquery as soon as it finds the first matching row.
The following SQL statement returns TRUE and lists the customer names if they have placed an order:
SELECT CustomerName FROM Customers WHERE EXISTS (SELECT OrderID FROM Orders WHERE Orders.CustomerID = Customers.CustomerID);
The result set would be:
| CustomerName |
|---|
| Alfreds Futterkiste |
| Ana Trujillo Emparedados |
Customer "Around the Horn" would not be listed because they have not placed any orders.