Advertisement
Intermediate SQL Server, Subqueries

What is the difference between using EXISTS and IN when checking for the presence of related data with a subquery?

Short answer

EXISTS checks only whether the subquery returns any rows at all, stopping as soon as it finds a match, which can be more efficient for large data sets, while IN compares a specific value against the full list of values returned by the subquery, and can behave unexpectedly if…

Save SQL Server mock interview
Advertisement
AModel answer
EXISTS checks only whether the subquery returns any rows at all, stopping as soon as it finds a match, which can be more efficient for large data sets, while IN compares a specific value against the full list of values returned by the subquery, and can behave unexpectedly if that list happens to contain a NULL value, sometimes leading to surprisingly no results at all.
-- EXISTS often performs better and avoids NULL related surprises
SELECT * FROM Customers c
WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId);
Real-world example
A developer switches a slow query using IN with a large subquery to use EXISTS instead, both improving performance and avoiding a subtle bug caused by an unexpected NULL value in the subquery's results.
Likely follow-ups
  • Why does a NULL value in the subquery results cause problems specifically with NOT IN?
  • Is there ever a case where IN is actually the better choice over EXISTS?
Related topics