Outer 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 later during this discussion.

I will be using the Adventure Works 2012 sample database supplied by Microsoft during this talk.

Let us start our exploration off by getting the business requirements for the query from the Sales & Marketing manager. (S)he wants to see if item color influences a customers choice of the product. I will be using the multiline table value function, [ufnColor2RgbValues], that I created in a previous blog.

Since both the CROSS and OUTER APPLY operators are very similar in nature, I want to compare and contrast their properties.

Think of the CROSS APPLY operator as a INNER JOIN with a correlated sub-query. The TSQL code below returns 30 rows. However, 14 rows were dropped from the result set due to them not having a color defined.

On the other hand, think of the OUTER APPLY operator as a LEFT JOIN with a correlated sub-query. Because of this property, all 44 rows of data are returned in the result set.

In a nutshell, the CROSS APPLY and OUTER APPLY operators are like two fraternal twins. Both have the common characteristic of joining data to a sub-query or table valued function. Nonetheless, they do not merge data the same way. This characteristic makes them not identical. One operator does a INNER JOIN and the other does a LEFT JOIN.

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

Next time I will be talking about the GROUP SETS which is part of my Summarizing Data Series.

Cross Apply Operator Output

Outer Apply Operator Output

Outer Apply Operator Example

Related posts

Leave a Comment