CROSS APPLY is one of those helpful things in SQL Server that most people don’t think of or may not even know about. In this article I’d like to talk about what the APPLY operator is and how we can use it to simply our sql statements.
The APPLY operator allows you to join a table to a table-valued function. A table-valued function is a function that will return a table with one or more columns. With the apply operator, you can pass values from the first table in to the table-valued function.
There are only 2 types of APPLY operators:
CROSS APPLY – Returns records when a value from both sides of the operator match. Like an INNER JOIN.
OUTER APPLY – Returns all rows from the other side of the operator and will return the value or NULL from the table-valued function. This is like an OUTER JOIN.
FROM Animal A
CROSS APPLY GetAnimalHabitat(A.AnimalTypeCode) H
In the example above, you can see that we join to the GetAnimalHabitat function using the CROSS APPLY. You can imagine that this function does a bunch of logic that is not visible in this query. If the GetAnimalHabitat function had 25 lines of code, you can see how this simplifies the above query dramatically.
The APPLY operator can simplify the code, but could be accomplished by joining to a sub query as well. One difference is that the function in the APPLY operator is being executed for every row in the outer table. If you use the APPLY operator, make sure that you test the speed of your query to make sure that it did not degrade performance.