Link to home
Start Free TrialLog in
Avatar of billy21
billy21

asked on

Clustered Index Scan Vs Clustered Index Seek

Please view the query/UDF posted in the following related question.

I'd like to know how I can design my indices so that a clustered index scan can be avoided.

https://www.experts-exchange.com/questions/20960243/Converting-Vertical-Data-to-Horizontal-Data-through-Aggregation.html

Thanks,

Billy.
Avatar of billy21
billy21

ASKER

I've also posted the related table structure.
Create Function dbo.SOSCurrentVary(@StartDate DateTime)
Returns Table
AS
Return
     Select Va.SOSID,
     Max(Case When Va.VDate = @StartDate Then Units End) CurUnits1,
     Max(Case When Va.VDate = @StartDate+1 Then Units End) CurUnits2,
     Max(Case When Va.VDate = @StartDate+2 Then Units End)  CurUnits3,
     Max(Case When Va.VDate = @StartDate+3 Then Units End)  CurUnits4,
     Max(Case When Va.VDate = @StartDate+4 Then Units End)  CurUnits5,
     Max(Case When Va.VDate = @StartDate+5 Then Units End)  CurUnits6,
     Max(Case When Va.VDate = @StartDate+6 Then Units End)  CurUnits7
     From SOSVary Va
     Group By Va.SOSID
)


In the query above, there's no restriction on fields that could make the query more selective and force index seek rather than index scan.
The optimiser will rely on statisitcs to decide what's better.

An index seek will be performed if the query is selective.
The query above obviously needs to make a scan because there's no condition on the SOSID

Index seek will result in a performance boost if, say, 95% of the rows can be excluded by your where clause

You could maybe make it more selective using an additional where clause

Check execution plan for
    Select Va.SOSID,
     Max(Case When Va.VDate = @StartDate Then Units End) CurUnits1,
     Max(Case When Va.VDate = @StartDate+1 Then Units End) CurUnits2,
     Max(Case When Va.VDate = @StartDate+2 Then Units End)  CurUnits3,
     Max(Case When Va.VDate = @StartDate+3 Then Units End)  CurUnits4,
     Max(Case When Va.VDate = @StartDate+4 Then Units End)  CurUnits5,
     Max(Case When Va.VDate = @StartDate+5 Then Units End)  CurUnits6,
     Max(Case When Va.VDate = @StartDate+6 Then Units End)  CurUnits7
     From SOSVary Va
     Where Va.VDate between  @StartDate and @StartDate+6
     Group By Va.SOSID

Avatar of billy21

ASKER

It still uses a clustered index scan but based on what you said, it sounds like it's necessary to use the scan.
ASKER CERTIFIED SOLUTION
Avatar of Hilaire
Hilaire
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial