SQL EXISTS Operator
SQL EXISTS operator is a type of operator in Structured Query Language (SQL) used to test for the existence of any data in a subquery. The EXISTS operator returns a Boolean value of TRUE or FALSE, indicating whether the subquery returns any rows.
Orders Table:
OrderID | CustomerID |
---|---|
1 | 10 |
2 | 20 |
3 | 30 |
Customers Table:
CustomerID | CustomerName |
---|---|
20 | Alice |
30 | Bob |
40 | Charlie |
Suppose we want to retrieve the CustomerID and CustomerName from the Customers table where the CustomerID exists in the Orders table. In that case, we can use the EXISTS operator in the following way:
1SELECT CustomerID, CustomerName 2FROM Customers c 3WHERE EXISTS ( 4 SELECT 1 5 FROM Orders o 6 WHERE c.CustomerID = o.CustomerID 7);
output:
CustomerID | CustomerName |
---|---|
20 | Alice |
30 | Bob |
As we can see from the output, the EXISTS operator returns only the rows from the Customers table where the CustomerID exists in the Orders table.