CROSS APPLY is the Ferrari of SQL join techniques.
It looks fancy, and it really is. ποΈ
β‘ Why CROSS APPLY Is Amazing
-
π§ Lets you join custom row-by-row logic
-
π Runs faster than correlated subqueries
-
π Works great with TOP, aggregates & ranking
-
πͺ Cleaner than temp tables
SELECT u.Id, x.LastOrder
FROM Users u
CROSS APPLY (
SELECT TOP 1 Amount AS LastOrder
FROM Orders o
WHERE o.UserId = u.Id
ORDER BY o.Date DESC
) x;
π‘ Bonus
Perfect for pagination, scoring, and βlatest recordβ lookups.
