Correlated Subqueries, EXISTS and APPLY
This lesson explains correlated subqueries, EXISTS and NOT EXISTS, and the APPLY operator for per-row logic.
Learning outcomes
After completing this lesson, you will be able to:
- Explain why NOT EXISTS is safer than NOT IN.
- Choose between EXISTS, a correlated scalar subquery and APPLY.
- Describe how indexes affect correlated query performance.
Correlated subqueries
A subquery is correlated when it references a column of the outer query, so logically it runs for each outer row. EXISTS returns true as soon as one matching row is found, which suits checks such as customers who ordered in the last 30 days. NOT EXISTS finds rows without a match. NOT IN gives the same result only when the subquery cannot return NULL; if it returns a NULL, NOT IN returns no rows at all, which is a common bug.
-- Customers with no order in the last year
SELECT c.CustomerID, c.Name
FROM Sales.Customer AS c
WHERE NOT EXISTS (SELECT 1 FROM Sales.Orders AS o
WHERE o.CustomerID = c.CustomerID
AND o.OrderDate >= DATEADD(year, -1, SYSUTCDATETIME()));
-- Each product with its latest order date (correlated scalar subquery)
SELECT p.ProductID, p.Name,
(SELECT MAX(o.OrderDate)
FROM Sales.OrderLines AS l JOIN Sales.Orders AS o ON o.OrderID = l.OrderID
WHERE l.ProductID = p.ProductID) AS LastOrdered
FROM Catalog.Product AS p;The optimizer usually transforms correlated subqueries into joins: EXISTS becomes a semi-join and NOT EXISTS an anti-semi-join, so they are not inherently slow, but an index on the correlated column (here Orders.CustomerID and OrderLines.ProductID) is essential.
EXISTS and correlation
CROSS APPLY and OUTER APPLY
A correlated scalar subquery returns one value. APPLY evaluates a table expression for each outer row and can return several columns and rows. The right side can be a derived table with TOP and ORDER BY, a table-valued function, OPENJSON or even VECTOR_SEARCH.
-- The three largest orders of each customer
SELECT c.CustomerID, t.OrderID, t.TotalDue
FROM Sales.Customer AS c
CROSS APPLY (SELECT TOP (3) o.OrderID, o.TotalDue
FROM Sales.Orders AS o
WHERE o.CustomerID = c.CustomerID
ORDER BY o.TotalDue DESC) AS t;The following comparison helps choose between the per-row constructs.
Which per-row construct?
Performance considerations
Correlated constructs perform well when the inner query can seek on an index for each outer row; without one, each evaluation scans the inner table. Plans show these as nested loops joins with the inner side executed once per outer row, so the number of outer rows and the cost of each inner lookup decide the total cost. For large outer sets, a set-based rewrite with a window function, such as ROW_NUMBER over all orders, can be cheaper than APPLY with TOP.
Correlated performance
Customers without orders
A query SELECT ... FROM Customer WHERE CustomerID NOT IN (SELECT CustomerID FROM Orders) suddenly returns no rows after a guest checkout feature started inserting orders with a NULL CustomerID. What should the developer change?
Rewrite the predicate with NOT EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerID = c.CustomerID). NOT IN compares the value with every subquery value, and a comparison with NULL is UNKNOWN, so no row qualifies once a NULL appears. NOT EXISTS ignores rows that do not match and is unaffected. Adding WHERE CustomerID IS NOT NULL to the subquery also fixes it, but NOT EXISTS is the robust pattern.
Why can NOT IN return no rows at all?
Show answer
If the subquery returns a NULL, every comparison with it is UNKNOWN, so no outer row qualifies.
Exam Tips
Remember for the exam
- Rows with no related rows: NOT EXISTS, not NOT IN when NULLs are possible.
- Several columns or rows per outer row: CROSS APPLY or OUTER APPLY.
- Index the correlated columns; each outer row triggers an inner lookup.
- A correlated scalar subquery must return at most one row.