I have been looking at CROSS / OUTER APPLY with a colleague and we’re struggling to find real life examples of where to use them.
I’ve spent quite a lot of time looking at When should I use CROSS APPLY over INNER JOIN? and googling but the main (only) example seems pretty bizarre (using the rowcount from a table to determine how many rows to select from another table).
I thought this scenario may benefit from OUTER APPLY:
Contacts Table (contains 1 record for each contact)
Communication Entries Table (can contain a phone, fax, email for each contact)
But using subqueries, common table expressions, OUTER JOIN with RANK() and OUTER APPLY all seem to perform equally. I’m guessing this means the scenario isn’t applicable to APPLY.
Please share some real life examples and help explain the feature!
Some uses for
APPLYare…1) Top N per group queries (can be more efficient for some cardinalities)
2) Calling a Table Valued Function for each row in the outer query
3) Reusing a column alias
4) Unpivoting more than one group of columns
Assumes 1NF violating table structure….
Example using 2008+
VALUESsyntax.In 2005
UNION ALLcan be used instead.