SQL Server performance - Subselect or Inner Join?

↘锁芯ラ 提交于 2019-12-14 03:51:11

问题


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


回答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.)




回答2:


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)


来源:https://stackoverflow.com/questions/5831603/sql-server-performance-subselect-or-inner-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!