Nov 4, 2015

Cross Apply vs Outer Apply in SQL Server

Cross Apply and Outer Apply comes under Apply Operator which was introduced in SQL Server 2005

Apply function allows to join a table to a table-valued function in such a way that function is invoked for each row returned from the table which you can't do with Join and is the main difference between Join and Apply
  • The Cross Apply only returns rows from the left side table if the table-valued-function returns rows.
  • The Outer Apply clause returns all the rows of the left side table regardless of whether table-valued-function returns any row or not. If no row is returned by table-valued-function, the columns that the table-valued-function returns are null.

Let's take an example to understand in more detail.

In the below example we have used split function (Table Valued Function) in which we would pass comma separated string and it would return a table

First understand and created split function before running the below snippet using the link : split function in SQL Server
declare @tab table(Category varchar(20), item varchar(max))
insert into @tab
select 'Vegetables', 'Carrot,Tomato' union all
select 'Fruits', 'Apple,Banana,Grape' union all
select 'Beverages', null

select t.Category, s.val as item
from   @tab t
cross apply dbo.split(item, ',') s

select t.Category, s.val as item
from   @tab t
outer apply dbo.split(item, ',') s
OUTPUT
Output

Look at the output.
  • First output with Cross Apply: No row with Category "Beverages" in the output
  • Second output with Outer apply: Getting a row with Category "Beverages" in the output
Reason for difference:
  • Function is returning null value for Category "Beverages" because there is null value in item column for "Beverages"

    Choose :
  • OR
  • To comment
No comments:
Write Comments