CROSS/OUTER APPLY
What you’ll learn
- Per-row subqueries/TVFs via
CROSS APPLYandOUTER APPLY.
-- Get the most recent order per customer
SELECT c.CustomerID, c.Name, x.TopOrderDate
FROM dbo.Customers AS c
CROSS APPLY (
SELECT TOP (1) OrderDate
FROM dbo.Orders o
WHERE o.CustomerID = c.CustomerID
ORDER BY o.OrderDate DESC
) AS x(TopOrderDate);
-- OUTER APPLY returns NULLs when the inner subquery is empty
Notes
CROSS APPLYis like an inner join to a per-row derived set;OUTER APPLYpreserves the left row.- Great for JSON shredding, string splitting, and topβNβperβgroup patterns.