Lesson 3 of 3 Advanced Query Techniques

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.

True or false

EXISTS and correlation

Exam skills 1.3.7

Decide whether each statement about correlated subqueries is true.

Log in to try this activity Interactive activities are free with an account.

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.

EXISTS / NOT EXISTS
ReturnsTrue or false
Typical useFilter by existence
Rows without a matchFiltered in or out
Choose when Existence checks
Correlated scalar subquery
ReturnsOne value per outer row
Typical useOne related value, such as a latest date
Rows without a matchNULL value
Choose when A single looked-up value
CROSS / OUTER APPLY
ReturnsRows and columns per outer row
Typical useTop N per row, TVFs, OPENJSON
Rows without a matchCROSS drops them, OUTER keeps them
Choose when Several values or rows per outer row
Sort into groups

Which per-row construct?

Exam skills 1.3.7

Choose the construct that fits each requirement.

Log in to try this activity Interactive activities are free with an account.

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.

Scenario questions

Correlated performance

Exam skills 1.3.7 · 2.2.3

Choose the explanation or fix for each performance problem.

Log in to try this activity Interactive activities are free with an account.
Worked example

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.

Check yourself

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.