MASTER TABLE
x------x--------------------x
| Id | Name |
x------x--------------------x
| 1 | A |
| 2 | B |
| 3 | C |
x------x--------------------x
DETAILS TABLE
x------x--------------------x-------x
| Id | PERIOD | QTY |
x------x--------------------x-------x
| 1 | 2014-01-13 | 10 |
| 1 | 2014-01-11 | 15 |
| 1 | 2014-01-12 | 20 |
| 2 | 2014-01-06 | 30 |
| 2 | 2014-01-08 | 40 |
x------x--------------------x-------x
I am getting the same results when LEFT JOIN and OUTER APPLY is used.
LEFT JOIN
SELECT T1.ID,T1.NAME,T2.PERIOD,T2.QTY
FROM MASTER T1
LEFT JOIN DETAILS T2 ON T1.ID=T2.ID
OUTER APPLY
SELECT T1.ID,T1.NAME,TAB.PERIOD,TAB.QTY
FROM MASTER T1
OUTER APPLY
(
SELECT ID,PERIOD,QTY
FROM DETAILS T2
WHERE T1.ID=T2.ID
)TAB
Where should I use LEFT JOIN AND where should I use OUTER APPLY
A
LEFT JOINshould be replaced withOUTER APPLYin the following situations.1. If we want to join two tables based on
TOP nresultsConsider if we need to select
IdandNamefromMasterand last two dates for eachIdfromDetailstable.which forms the following result
This will bring wrong results ie, it will bring only latest two dates data from
Detailstable irrespective ofIdeven though we join withId. So the proper solution is usingOUTER APPLY.Here is the working : In
LEFT JOIN,TOP 2dates will be joined to theMASTERonly after executing the query inside derived tableD. InOUTER APPLY, it uses joiningWHERE M.ID=D.IDinside theOUTER APPLY, so that eachIDinMasterwill be joined withTOP 2dates which will bring the following result.2. When we need
LEFT JOINfunctionality usingfunctions.OUTER APPLYcan be used as a replacement withLEFT JOINwhen we need to get result fromMastertable and afunction.And the function goes here.
which generated the following result
3. Retain
NULLvalues when unpivotingConsider you have the below table
When you use
UNPIVOTto bringFROMDATEANDTODATEto one column, it will eliminateNULLvalues by default.which generates the below result. Note that we have missed the record of
Idnumber3In such cases an
APPLYcan be used(eitherCROSS APPLYorOUTER APPLY, which is interchangeable).which forms the following result and retains
Idwhere its value is3