I have a question concerning best-practices for indexing in SQL Server (or any RDBMS for that matter). Take the following table:
ProfileID int
Text nvarchar(50)
ProfileID is joined to a Profile table. For each profile, each Text must be unique. Therefore I put a Primary cover key on both columns. Fine.
However, I also want to be able to query the above table by ProfileID. So I also put an index on ProfileID too.
This means I have an overlapping index. I don’t know if this is a total waste since there is a cover index already, or if it’s correct since the cover index would be a hash of the two columns (or am I misunderstanding cover indexes)?
Edit:
I created the index in the order (ProfileID, Text). What if, for argument’s sake, there were 3 columns A, B, and C, that had a cover index over all 3. Would it only benefit if we queried against “A” or “A, B, and C”, but not “B”, or “C”, or “B and C”?
An index on
(ProfileID, Text)(in this order) is an index onProfileIDas well.You may still want to create an additional index on
ProfileIDonly, if you want greaterSELECTperformance on queries that do not involveText.However, this has two drawbacks:
Maintaining two indexes requires more resources and performance of
DMLqueries (INSERT,UPDATE,DELETE) may sufferIf you mix queries of the two types, both indexes will occupy the cache and there can be more cache misses than with a single index.
It is not a problem if your table is small enough to fit into the cache along with both indexes.
A truly covering index would be created this way:
This way,
Textwould only be stored in leaf-level nodes of the index.However, since you need a
UNIQUEindex, both columns need to be parts of the key. The nodes are sorted lexicographically onProfileIDthenText.