Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when choose CROSS APPLY and when EXISTS?

I read, CROSS APPLY is just like JOIN.. and I think JOIN can be accomplished with EXISTS also (correlated sub query)

I am confused, what is the difference in using CROSS APPLY and EXISTS?

when should I go for CROSS APPLY against EXISTS?

like image 483
dotNETbeginner Avatar asked Mar 12 '12 11:03

dotNETbeginner


People also ask

When we use cross apply in SQL Server?

The most common practical use of the CROSS APPLY is probably when you want to make a JOIN between two (or more) tables but you want that each row of Table A math one and only one row of Table B. In the following example, in more detail, each user (Table A) will match with its longest trip (Table B).

What does it mean to cross apply?

CROSS APPLY in SQL Server CROSS APPLY returns only rows from the outer table that produce a result set from the table-valued function. It other words, result of CROSS APPLY doesn't contain any row of left side table expression for which no result is obtained from right side table expression.

What is the difference between cross apply and cross join?

In simple terms, a join relies on self-sufficient sets of data, i.e. sets should not depend on each other. On the other hand, CROSS APPLY is only based on one predefined set and can be used with another separately created set.


1 Answers

CROSS APPLY isn't just like a JOIN. A JOIN finds matching (or not matching) rows between two sets of data. CROSS APPLY is a method to run a query against every row of the thing you're applying it against. This can act as a filtering mechanism, something like how a JOIN works, but it's applying something to each row, so it needs to be thought of that way.

EXISTS in a sub-query is a completely different mechanism of filtering. It's a method of quick identification because it immediately short-circuits it's search when it finds something. The place you'd want to use EXISTS in general is when you're likely to get a hit on the filter criteria, thereby making the searches as short as possible. But, EXISTS doesn't find all matches. It just finds the first match and then stops searching.

So while you can arrive at the same results from these three different methods, use them as defined and you'll usally be right. If you're literally JOINing two sets of data, use JOIN. If you want to run a process, frequently a filter, against every row in a data set, use CROSS APPLY. If you want a fast filter on a likely positive match, use EXISTS.

like image 152
Grant Fritchey Avatar answered Sep 25 '22 12:09

Grant Fritchey