Cross Apply Operator

The SELECT reserved word is part of the Data Manipulation Language (DML) defined by Codd and is used to query data from the database. Because of its popularity, there are many clauses and functions that can be used to construct a query to retrieve data.

Today, I am continuing our exploration of this reserved word by reviewing queries that merge data using the APPLY operator. The APPLY operator come in two flavors: CROSS and OUTER. I am going to concentrate on the former during this discussion.

I will be using the Adventure Works 2012 sample database supplied by Microsoft during this talk. The SQL snippet below uses a simple GROUP BY clause to determine the distribution of Sales Orders by year.

Let us start our exploration off by getting the business requirements for the query from the Sales & Marketing manager. (S)he noticed that the order date posts two days late in our home grown ERP system. We need to adjust the current summary query to fix this date issue.

The example below is really cool. Think of the CROSS APPLY operator as a INNER JOIN with a correlated sub-query. For added clarity, we can even make it look like a table value function by supplying a column alias at the table alias level.

The code below produces the same result as the one above. In fact, the query plans are exactly the same. However, the example above is cleaner and self documenting. We are using a adjusted date.

I want to thank Paul White for debating this with me on a forum post. That is how we learn things.

Last but not least, you will see the CROSS APPLY operator used mostly with Dynamic Management Functions which are table value functions.

The snippet below does a sample call to the [ufnGetContactInformation] function for a single record. Then, it cross applies the function against all orders in Australia in a SELECT statement.

In a nutshell, the CROSS APPLY operator is kinda mandatory when using the Dynamic Management Functions in a query.

However, there are other uses for this construct. I showed you one example in which a calculation would have been coded all over the place in the aggregation query. By using the CROSS APPLY, we made the query more readable and simplistic.

If you have a correlated sub query in the future, think about using this construct. Check out Rob Farley’s article and his thoughts on the subject.

Next time I will be talking about the OUTER APPLY operator.

Cross Apply Operator Example

Related posts

One Thought to “Cross Apply Operator”

  1. Thanks for laboring so hard to make an important point.

Leave a Reply to Daniel Adeniji Cancel reply