Advertisement
Intermediate SQL Server, Subqueries

What are common mistakes developers make when writing subqueries that can lead to incorrect results or poor performance?

Short answer

Common mistakes include using NOT IN with a subquery that might return NULL values, leading to unexpectedly empty results, writing a correlated subquery when a simple join would perform significantly better, and forgetting that a subquery returning multiple rows will cause an…

Save SQL Server mock interview
Advertisement
AModel answer
Common mistakes include using NOT IN with a subquery that might return NULL values, leading to unexpectedly empty results, writing a correlated subquery when a simple join would perform significantly better, and forgetting that a subquery returning multiple rows will cause an error if used in a context expecting only a single scalar value.
-- Problematic if OrderId can contain NULL
SELECT * FROM Customers WHERE CustomerId NOT IN (SELECT CustomerId FROM Orders WHERE CustomerId IS NOT NULL);
Real-world example
A developer debugging a report that mysteriously returned zero results discovers a NOT IN subquery was silently failing due to an unexpected NULL value, and fixes it by explicitly filtering out NULLs or switching to NOT EXISTS instead.
Likely follow-ups
  • How do you defensively write subqueries to avoid this kind of NULL related issue?
  • What error occurs when a subquery expected to return one value actually returns several?
Related topics