HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Index included columns

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
indexcolumnsincluded

Problem

After running a fairly hefty query, the execution plan gave me a missing index suggestion which was of the form:

(Timestamp) INCLUDE (CustomerID, EventID, ID, EmployeeID)

Which seems to be a covering index (the INCLUDE column are all either primary keys (ID) or foreign keys). However, my querys WHERE clause is filtering by Timestamp, CustomerID, and EventID. I don't know why these weren't included in the main part of the index.

So my question is, is there any difference in using the suggested index above, or what I think is a better alternative;

(Timestamp, CustomerID, EventID) INCLUDE (ID, EmployeeID)

My understanding is that this will still allow Timestamp-only index seeking, but will also further assist my query by having the customer and event IDs (which are filtered) in the main part.

I think this was something to do with the width of the 'main' part - FYI, Timestamp is a datetime2(0), CustomerID is an int, and EventID is a byte.

I am testing this myself at the moment, but this is a HUGE table - over 1,000,000,000 rows - and it is taking time to compare the indexes. That, and I'd like to learn more about this.

Thanks.

Solution

Probably Timestamp is very selective, possible even unique. As such there is no point in adding other fields to the key, they will only increase the size of the key without contributing to the selectivity. Having them as INCLUDED columns instead allows them to be added only to the leaf pages, saving on the overall size of the index.

select top(1000) count(*) as cnt, Timestamp 
from ...
group by Timestamp
order by cnt desc;


What does the above return?

Code Snippets

select top(1000) count(*) as cnt, Timestamp 
from ...
group by Timestamp
order by cnt desc;

Context

StackExchange Database Administrators Q#33596, answer score: 5

Revisions (0)

No revisions yet.