SQL EXISTS

The EXISTS operator is used to check the existence of rows in a subquery. It returns TRUE if the subquery returns one or more rows, and FALSE if it returns no rows.

Syntax

The basic syntax for EXISTS is:


SELECT column1, column2
FROM table1
WHERE EXISTS (subquery);

        

Example

Suppose we have two tables: Customers and Orders. To find customers who have placed at least one order, we can use:


SELECT CustomerID, CustomerName
FROM Customers
WHERE EXISTS (
    SELECT 1
    FROM Orders
    WHERE Orders.CustomerID = Customers.CustomerID
);