I'm trying to expand my humble SQL query skills and I have stumbled across the CROSS APPLY.
I have an example from a book and I kind of get it but I just want to clarify a few things.
I want to understand when you would use a CROSS APPLY and what the benefits are.
It seems to me the benefits dictate when you would use CROSS APPLY.
Benefits
I believe the benefits are to reduce the number of times a function is called for rows in a query.
Instead of running the function for every possible row in a big SELECT you can use CROSS APPLY
to only run the function against rows returned on the outer query selection to reduce the amount of resources it takes to get the returned query results.
When To Use
To increase performance by running a function against less rows than necessary.
Questions
1) Is my ‘Benefits’ description accurate – if not what is missing?
2) Is my ‘When To Use’ description accurate – if not what else is there to consider?
3) Does it make any difference if the CROSS APPLY function returns a set of ROWS or
single aggregate?
Context
For context, here is the example from the book.
Dazed and confused.
Remember.. 'Depression is just anger without enthusiasum'.
I have an example from a book and I kind of get it but I just want to clarify a few things.
I want to understand when you would use a CROSS APPLY and what the benefits are.
It seems to me the benefits dictate when you would use CROSS APPLY.
Benefits
I believe the benefits are to reduce the number of times a function is called for rows in a query.
Instead of running the function for every possible row in a big SELECT you can use CROSS APPLY
to only run the function against rows returned on the outer query selection to reduce the amount of resources it takes to get the returned query results.
When To Use
To increase performance by running a function against less rows than necessary.
Questions
1) Is my ‘Benefits’ description accurate – if not what is missing?
2) Is my ‘When To Use’ description accurate – if not what else is there to consider?
3) Does it make any difference if the CROSS APPLY function returns a set of ROWS or
single aggregate?
Context
For context, here is the example from the book.
Code:
SELECT S.Supplierid, s.companyname AS Supplier, A.*
FROM Production.Suppliers AS S
CROSS APPLY (SELECT productid, productname, unitprice
FROM Production.Products AS P
WHERE P.Supplierid = S.Supplierid
ORDER BY unitprice, productid
OFFSET 0 ROWS FETCH FIRST 2 ROWS ONLY) AS A
WHERE S.Country = ‘N’Japan;
Dazed and confused.
Remember.. 'Depression is just anger without enthusiasum'.