SQL Server Non Clustered Indexes with multiple columns

3.6k views Asked by At

I cannot seem to find a straight answer. I have the following columns:

ZipCode
StateAbbreviation
CountyName

I will be querying the table by either ZipCode alone or StateAbbreviation/CountyName combination. I have a PK Id column defined, so this is my clustered index.

What is recommended approach to achieve better performance/efficiency? What kind of indexes should I create considering how I will be searching the table?

2

There are 2 answers

0
marc_s On BEST ANSWER

First - run your app and see if it's fast enough without any indexes.

Second - if it's slow in some places, find the SQL workload that this code generates - what kind of queries do you have? Try adding an index on either ZipCode or on (StateAbbreviation, CountyName) and then run your app again and see how it performs.

If that one index solved your issue -> go enjoy your spare time! :-)

If not: add the second index and see if that help.

Don't overdo indexes just because you can! One at a time, only when it hurts. Don't just add indexes ahead of time - only add when you have a perf problem. And to see if it helps, you need to measure, measure, and measure again and compare to a previous baseline of measurements.

Nonclustered indexes are being used surprisingly rarely - your queries need to be just right for a nonclustered index to even be considered by the SQL Server query optimizer. If the table is "too small", a table scan will be preferred. If you use SELECT * all the time - your nonclustered indexes are likely to be ignored, too.

0
ps2goat On

If you do add indexes, the columns should be ordered in the index using the same order as your queries. If you don't do that, there's no guarantee the index will be used. Index 1) Zipcode; Index 2) State Abbreviation, CountyName.

As @marc_s as said, indexes should be used when they are necessary as they do create some additional overhead when rows are modified/inserted/deleted. If they are straight-up reference tables, though, the only negative impact an index would have is the disk space that it uses. I usually find that to be worth less than no index.