Advertisement
Beginner SQL Server, Subqueries

What is the difference between a correlated and a non correlated subquery?

Short answer

A non correlated subquery runs independently and only once, producing a fixed result that the outer query then uses, while a correlated subquery references a column from the outer query, meaning it effectively runs once for each row processed by the outer query, since its result…

Save SQL Server mock interview
Advertisement
AModel answer
A non correlated subquery runs independently and only once, producing a fixed result that the outer query then uses, while a correlated subquery references a column from the outer query, meaning it effectively runs once for each row processed by the outer query, since its result depends on the current row being evaluated.
-- Non correlated: runs once, independent of outer query
SELECT * FROM Customers WHERE CustomerId IN (SELECT CustomerId FROM Orders);

-- Correlated: references the outer query's current row
SELECT * FROM Customers c
WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId);
Real-world example
A report finds customers with at least one order using a correlated subquery with EXISTS, which checks for a matching order specifically tied to each individual customer row being evaluated by the outer query.
Likely follow-ups
  • Why can correlated subqueries sometimes be slower than an equivalent join?
  • When would EXISTS be preferred over IN for this kind of check?
Related topics