简体   繁体   中英

Why does nonclustered index column still do index scan instead of index seek

I have the following tables

EmployeePatientLink

Id nvarchar(128) PK & clustered index
PatientId nvarchar(128) FK NULL -- nonclustered index created
EmployeeId int NULL-- nonclustered index created. 

Patient

Id nvarchar(128) PK & clustered index
Id PK & clustered Index  -- this links to above table 

PatientSchedule

PatientId nvarchar(128) NULL -- nonclustered index created

and this query

select 
    Id, PatientId 
from 
    PatientSchedule ps
Inner join 
    EmployeePatientLink ep on ps.PatientId = ep.PatientId
    where ep.EmployeeId=1111 

I do have have similar queries like above and others perform index seek in the execution plan and Nested Loop joins.

However this one always includes Merge Join and Sort and Index scan.

I guess I have sufficient indexes created and everything is in order and it should be doing index seek.

Is there a specific reason why query optimizer chooses index seek?

Try create index with included columns to avoid "key lookup" (SQL Server need search for PatientId value when EmployeeId is found)

CREATE INDEX IX_EmployeePatientLink_EmployeeId ON EmployeePatientLink(EmployeeId) 
INCLUDE (PatientId)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM