I have small question about SQL Server. When do we use cross apply
, and when do we use inner join
? Why use cross apply
at all in SQL Server?
I have emp, dept tables; based on those two tables, I write an inner join
and cross apply
query like this:
----using cross apply
SELECT *
FROM Department D
CROSS APPLY
(SELECT *
FROM Employee E
WHERE E.DepartmentID = D.DepartmentID) A
----using inner join
SELECT *
FROM Department D
INNER JOIN Employee E ON D.DepartmentID = E.DepartmentID
Both queries return the same result.
Here why is cross apply
needed in SQL Server? Is there performance difference? Can you please tell me?
When will we use cross apply
and when inner join
? Any performance difference between these queries? Please tell me which is the best way to write this query in SQL Server.
INNER JOIN
andCROSS APPLY
(same withLEFT JOIN
andOUTER APPLY
) are very closely related. In your example I'd assume, that the engine will find the same execution plan.JOIN
is a link between two sets over a conditionAPPLY
is a row-wise sub-callBut - as mentioned above - the optimizer is very smart and will - at least in such easy cases - understand, that it comes down to the same.
JOIN
will try to collect the sub-set and link it over the specified conditionAPPLY
will try to call the related result with the current row's values over and over.Differences are in calling table-valued-functions (should be inline-syntax!), with XML-method
.nodes()
and with more complex scenarios.One example how one could use
APPLY
to simulate variables...to use the result of a row-wise calculation like you'd use a variable:
This is the same as the following, but much easier to read (and type):
One example with XML-method
.nodes()
The result
And one example for an inlined function call
The result