Question

I am trying to optimize some stored procedures and they are very frequently using EXISTS, ANY or IN and I want to know the difference in what specific scenario which is best either IN, Exists or ANY.

I created three queries using IN, EXISTS and ANY and checked the execution cycle of them but the execution cycle of all three queries are same. I am confused why it is coming same, how can the execution cycle be different or what are the scenarios where it can be different. Below are the three queries and execution cycle of them that I tried. Can anyone give me an example how the execution cycle can be changed, please share any scenario or query.

Query using EXISTS

One more question here in the subquery, what is the need of * or columns specified?

SELECT * FROM RecastEvents AS re
    WHERE EXISTS (Select * FROM Metadata 
                      WHERE EventId = 2145984 AND EventId = re.CCId)

Execution Cycle of Exists

Query using IN

SELECT * FROM RecastEvents as re
    WHERE re.CCID IN (SELECT EventId FROM Metadata
                          WHERE EventId = 2145984)

Execution Cycle of IN

Query using ANY

SELECT * FROM RecastEvents AS re
    WHERE re.CCID = ANY (SELECT EventId FROM Metadata 
                             WHERE EventId = 2145984)

enter image description here

Was it helpful?

Solution

It is coming out the same because the query optimizer is doing its job.

One of the purposes of SQL (and similar languages) is that you write a query specifying what you want, and not how you want it, and let the query system deal with the how.

In this case the query optimizer rules end up with the same actual query execution plan. This may or may not change depending on the volume of data later on. My guess is it won't.

As for the * in the first, you can try with 1 instead and it'll work out fine, it is used as a placeholder for "data" in this case.

OTHER TIPS

In sql server 2005 and older versions, EXISTS would be faster coz once its found its record, it will come out of process. Whereas IN will collect all the data from sub query for processing.

But in latest versions of sql server query optimizer is smart enough to generate typically better plan

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top