3

I've been pondering the question which of those 2 Statements might have a higher performance (and why):

select * from formelement 
where formid = (select id from form where name = 'Test')

or

select * 
from formelement fe 
inner join form f on fe.formid = f.id 
where f.name = 'Test'

One form contains several form elements, one form element is always part of one form.

Thanks,

Dennis

3
  • 2
    Run them both and compare execution plans... Commented Apr 29, 2011 at 11:52
  • Nice Idea, to be honest I had no Idea this feature existed. But while this answers the question what exactly needs performance, it doesn't really inform me about why that is. Commented Apr 29, 2011 at 11:56
  • I removed my answer :) For the execution plans, they WILL tell you why. You will see if the operations are different, and the type of operations executed will give you the reasoning. Commented Apr 29, 2011 at 12:01

2 Answers 2

3

look at the execution plan, most likely it will be the same if you add the filtering to the join, that said the join will return everything from both tables, the in will not

I actually prefer EXISTS over those two

select * from formelement  fe
where exists (select 1 from form f 
                 where f.name='Test' 
                 and fe.formid =f.id)
Sign up to request clarification or add additional context in comments.

2 Comments

IN would be equivalent to exists for this as well, correct (exec plan wise)?
Yes, should be the same, I like exists more because you don't have to worry about NULLS or if you mistype the column name which won't throw an error if the column name exists in the formelement table. Example here: forum.lessthandot.com/viewtopic.php?f=17&t=14123
1

The performance depends on the query plan choosen by the SQL Server Engine. The query plan depends on a lot of factors, including (but not limited to) the SQL, the exact table structure, the statistics of the tables, available indexes, etc.

Since your two queries are quite simple, my guess would be that they result in the same (or a very similar) execution plan, thus yielding comparable performance.

(For large, complicated queries, the exact wording of the SQL can make a difference, the book SQL Tuning by Dan Tow gives a lot of great advice on that.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.