OUTER APPLY in Sql Server

OUTER APPLY operator in Sql Server returns all rows from the LEFT table expression of the OUTER APPLY operator irrespective of whether it produces the corresponding result in the RIGHT table expression or not. The RIGHT table expression columns value will be NULL in the final result for those rows in the LEFT table expression that don’t produce the result from the RIGHT table expression. So from the result perspective we can say that the OUTER APPLY is similar to the classic LEFT OUTER JOIN

To understand OUTER APPLY in Sql Server with extensive list of examples, let us create the demo tables with sample data as shown in the following image by executing the following script:

apply-operator-demonstration-tables

CREATE DATABASE SqlHintsOUTERAPPLYDemo
GO
USE SqlHintsOUTERAPPLYDemo
GO
--Create Customers Table and Insert records
CREATE TABLE Customers 
( CustomerId INT, Name VARCHAR(50) )
GO
INSERT INTO Customers(CustomerId, Name) 
VALUES(1,'Shree'), (2,'Kalpana'), (3,'Basavaraj')
GO
--Create Orders Table and Insert records into it
CREATE TABLE Orders
(OrderId INT, CustomerId INT,Amount MONEY, OrderDate DATETIME)
GO
INSERT INTO Orders(OrderId, CustomerId,Amount,OrderDate) 
VALUES(100,1,100.0,Getdate()-30), (101,1,200.0,Getdate()-20),
      (103,1,300.0,Getdate()-10), (104,2,150.0,Getdate())	
GO

Create a Table Valued Function

Now execute the following script to create an inline Table valued function fnGetLastTwoCustomerOrders, which returns order details of the last 2 orders corresponding to the input customer id.

CREATE FUNCTION dbo.fnGetLastTwoCustomerOrders
( @CustomerId AS INT )  
RETURNS TABLE 
AS 
RETURN ( 
		SELECT TOP 2 * 
		FROM Orders O 
		WHERE O.CustomerId = @CustomerId 
		ORDER BY OrderDate DESC
	)

Let us verify this functions result for the customer id = 1

--Return last two order details for the customer id = 1
SELECT * FROM dbo.fnGetLastTwoCustomerOrders(1) O
GO

RESULT:
apply-operator-table-valued-function-result

OUTER APPLY Examples

Example 1: Demonstrates how we can re-write a very basic LEFT OUTER JOIN query by OUTER APPLY operator

OUTER APPLY is not an alternative for LEFT OUTER JOIN, instead each of them have their own pros and cons. The general rule of thumb is you may like to use the OUTER JOIN if you want to evaluate/execute the RIGHT side table expression or Table Valued function for each row in the LEFT side table expression. Just to demonstrates how we can use OUTER APPLY operator with a very basic example, here in this example will re-write a very basic LEFT OUTER JOIN query by OUTER APPLY.

We can write a query like below by using LEFT OUTER JOIN to get all Customers table rows irrespective of whether a corresponding record exists in the Orders table or not. For the records in the Customers table which don’t have matching records in the Orders table, the Orders table columns in the result will have NULL values

SELECT *
FROM Customers C
        LEFT OUTER JOIN Orders O
	   ON C.CustomerId = O.CustomerId

RESULT
left-outer-join-query

We can re-write the above LEFT OUTER JOIN query using OUTER APPLY as shown below and still get the same result

SELECT *
FROM Customers C
  OUTER APPLY (SELECT * 
               FROM Orders O
     	       WHERE O.CustomerId = C.CustomerId) ORD

RESULT
outer-apply-left-outer-join-equivalent

From the above results we can see that the re-written OUTER APPLY query is returning the same result as that of the LEFT OUTER JOIN query.

[ALSO READ] CROSS APPLY in Sql Server

Example 2: OUTER APPLY operator between a Table and user defined Table Valued Function

We can write a query like below using OUTER APPLY operator to get details of all the customers with their last two order details if it is present. This query basically evaluates the function fnGetLastTwoCustomerOrders for each row in the Customer table by taking CustomerId as the input.

SELECT *
FROM dbo.Customers C
      OUTER APPLY 
        dbo.fnGetLastTwoCustomerOrders(C.CustomerId) O

RESULT:
sql-server-outer-apply-example-1

From the result we can see that for the customer with customer id =1, we have two orders in the result even though this customer has three orders because the function fnGetLastTwoCustomerOrders returns at max the last two orders for any given CustomerId. And for CustomerId =2, we see only one order detail in the result as this customer has placed only one order till now and for the Customer with CustomerId = 3 in the result we can see only the Customer details and all the Order details columns value for this customer is NULL because this customer is yet to place any order.

[ALSO]

[ALSO READ] Sql Server APPLY operator

Example 3: OUTER APPLY operator between a Table and Table Expression

In the example 2 the RIGHT side of the OUTER APPLY operator was User Defined Function, this example demonstrates how we can have a Table Expression on the right side of this operator.

The below script can also achieve the same result as the example 2, but here we have not used the Table Valued Function fnGetLastTwoCustomerOrders instead we have used the derived table.

SELECT *
FROM dbo.Customers C
	OUTER APPLY (SELECT TOP 2 * 
	  	     FROM Orders O 
		     WHERE O.CustomerId = C.CustomerId 
		     ORDER BY OrderDate DESC) ORD

RESULT:
sql-server-outer-apply-example-2

4 thoughts on “OUTER APPLY in Sql Server

  1. Type mistake here, “We can re-write the above INNER JOIN query using CROSS APPLY as shown below and still get the same result” instead of INNER it should be LEFT and “OUTER APPLY” instead of CROSS APPLY.

Leave a Reply

Your email address will not be published. Required fields are marked *