I discovered that in some cases a query like
select
usertable.userid,
(select top 1 name from nametable where userid = usertable.userid) as name
from usertable
where active = 1
takes an order of magnitude longer to complete in SS2008R2 than the equivalent join query
select
usertable.userid,
nametable.name
from usertable
left join nametable on nametable.userid = usertable.userid
where usertable.active = 1
where both tables are indexed and have over 100k rows. Interestingly, inserting a top clause into the original query makes it perform on par with the join query:
select
top (select count(*) from usertable where active = 1) usertable.userid,
(select top 1 name from nametable where userid = usertable.userid) as name
from usertable
where active = 1
Does anyone have any idea why the original query performs so poorly?
Well, the queries are different – unless the
useridcolumn is a primary key or has a uniqueness constraint then the second query could return more rows than the first.That said, with the assumption that userid is a primary key / unique try removing the
TOP 1part of the first subquery: