Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

MS SQL SERVER APPLY AND JOIN Keyword

4.45/5 (6 votes)
16 Mar 2014CPOL1 min read 13K  
Tip on CROSS APPLY and OUTER APPLY

Introduction

This tip just provides a difference between apply keyword that was introduced by MSSQL server 2005 and join keyword. The developer should clearly know the difference between apply and join to tune SQL query.

Using the Code

First, create two tables as mentioned below:

Image 1

Image 2

And insert few records in that table. For example, you can see that I inserted few records in both tables.

SQL
SELECT * FROM EMPLOYEE
SELECT * FROM DEPARTMENT  

Image 3

I am going to demonstrate cross apply behaves the same like inner join. You can find the same result from both queries that use inner join and cross join. For example, you see from below:

SQL
SELECT E.EMPID,E.NAME,E.DEPTID,D.NAME FROM EMPLOYEE E 
INNER JOIN  DEPARTMENT D
ON E.DEPTID=D.DEPTID

SELECT E.EMPID,E.NAME,E.DEPTID,CA.NAME FROM EMPLOYEE E
CROSS APPLY(
SELECT * FROM DEPARTMENT D WHERE D.DEPTID=E.DEPTID
) CA  

Image 4

From the above result, it is clear that both produce the same result. Now, take a look at both query execution plans.

Image 5

From the above execution plan, it is clear that both queries have the same execution plan.

Now I am going to demonstrate outer apply with left join. outer apply is the same as left join. You can see from the below mentioned query and both results. For example:

SQL
SELECT E.EMPID,E.NAME,E.DEPTID,D.NAME FROM EMPLOYEE E 
LEFT JOIN  DEPARTMENT D
ON E.DEPTID=D.DEPTID
SELECT E.EMPID,E.NAME,E.DEPTID,OA.NAME FROM EMPLOYEE E
OUTER APPLY(
SELECT * FROM DEPARTMENT D WHERE D.DEPTID=E.DEPTID
) OA

Image 6

From the above result, you can see both the queries produce the same result. Now, take a look at the execution plan.

Image 7

From the execution plan, you can see both queries have the same execution plan.

I hope this tip will help you. If you have any suggestions, then you are welcome.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)