SQL Server Interview Question #73

What is EXISTS?

Joins, Subqueries, CTEs & Set Operators Mid-Level Intermediate

Detailed Explanation

EXISTS tests whether a subquery returns at least one row. The values selected inside the EXISTS subquery are not important; SELECT 1 is a common convention.

EXISTS is especially useful for semi-join logic such as returning customers who have orders or categories that contain products. SQL Server can stop searching for a match once existence has been established, depending on the execution plan.

Code Example

SELECT c.Id, c.Name
FROM dbo.Customers AS c
WHERE EXISTS
(
    SELECT 1
    FROM dbo.Orders AS o
    WHERE o.CustomerId = c.Id
);