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
In your example queries the results are indeed the same.
But
OUTER APPLY
can do more: For each outer row you can produce an arbitrary inner result set. For example you can join theTOP 1 ORDER BY ...
row. ALEFT JOIN
can't do that.The computation of the inner result set can reference outer columns (like your example did).
OUTER APPLY
is strictly more powerful thanLEFT JOIN
. This is easy to see because eachLEFT JOIN
can be rewritten to anOUTER APPLY
just like you did. It's syntax is more verbose, though.A
LEFT JOIN
should be replaced withOUTER APPLY
in the following situations.1. If we want to join two tables based on
TOP n
resultsConsider if we need to select
Id
andName
fromMaster
and last two dates for eachId
fromDetails
table.which forms the following result
This will bring wrong results ie, it will bring only latest two dates data from
Details
table irrespective ofId
even though we join withId
. So the proper solution is usingOUTER APPLY
.Here is the working : In
LEFT JOIN
,TOP 2
dates will be joined to theMASTER
only after executing the query inside derived tableD
. InOUTER APPLY
, it uses joiningWHERE M.ID=D.ID
inside theOUTER APPLY
, so that eachID
inMaster
will be joined withTOP 2
dates which will bring the following result.2. When we need
LEFT JOIN
functionality usingfunctions
.OUTER APPLY
can be used as a replacement withLEFT JOIN
when we need to get result fromMaster
table and afunction
.And the function goes here.
which generated the following result
3. Retain
NULL
values when unpivotingConsider you have the below table
When you use
UNPIVOT
to bringFROMDATE
ANDTODATE
to one column, it will eliminateNULL
values by default.which generates the below result. Note that we have missed the record of
Id
number3
In such cases an
APPLY
can be used(eitherCROSS APPLY
orOUTER APPLY
, which is interchangeable).which forms the following result and retains
Id
where its value is3