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:

OrderIDCustomerID
110
220
330

Customers Table:

CustomerIDCustomerName
20Alice
30Bob
40Charlie

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:

CustomerIDCustomerName
20Alice
30Bob

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.