Why does SQL Server perform a clustered scan when IN clause has a subquery? -
if search users so:
select * userprofile userid in (1, 2, 3)
the execution plan shows userprofile using clustered index seek
if change in clause use subquery:
select * userprofile userid in ( select distinct senders.userid messages m join usermessages recipients on recipients.messageid = m.messageid join usermessages senders on senders.messageid = m.messageid recipients.typeid = 2 , recipients.userid = 1 , senders.userid <> 1 , senders.typeid = 1 )
the execution plan shows subquery using clustered index seek userprofile outer query using clustered index scan.
how can write both inner , outer queries using seeks?
a set of seeks cheaper full scan if rowcount low. sql server pretty conservative if there chance many records found, prefers scan. in example, it's pretty clear userid in (1,2,3)
not return many rows. subquery, sql server can't tell.
you can force seek with:
from userprofile (forceseek)
Comments
Post a Comment