I’d appreciate some advice from SQL Server gurus here. Let me explain…
I have an SQL Server 2008 database table that has 21 columns. Here’s a quick type of those:
- INT Primary Key
- Several other INT’s that are indexes already (used to reference this and other tables)
- Several NVARCHAR(64) to hold user-provided text
- Several NVARCHAR(256) to hold longer user-provided text
- Several DATETIME2
- One BIGINT
- Several UNIQUEIDENTIFIER, one is already an index
The way this table is used is that it is presented to a user as a sortable table and a user can choose which column to sort it by. This table may contain many thousands of records (like currently it does 21,000 and it will be growing.)
So my question is, do I need to set each column as an INDEX to enable faster sorting?
PS. Forgot to say. The output obviously supports pagination, so the user sees no more than 100 rows at once.
Contrary to popular belief, just having an index on a column does not guarantee that any queries will be any faster!
If you constantly use
SELECT *..from that table, these non-clustered indices on a single column will most likely not be used at all.A good nonclustered index is a covering index, which means, it contains all the necessary columns to satisfy one or multiple given queries. If you have this situation, then a nonclustered index can make sense – otherwise, in more cases than not, the nonclustered index is likely to be ignored by the query optimizer. The reason for this being: if you need all the columns anyway, the query would have to do key lookups from the nonclustered index into the actual data (the clustered index) for each row found – and the key lookup is a very expensive operation, so doing this for a lots of hits becomes overly costly, and the query optimizer will rather quickly switch to a index scan (possibly the clustered index scan) to fetch the data.
Don’t over-index – use a well-designed clustered index, put indices on the foreign key columns to speed up joins – and then let it be for the time being. Observe your system, measure performance, maybe add an index here or there – but don’t just overload the system with tons of indices!
Having too many indices can be worse than having none – every index must be maintained, e.g. updated for each
INSERT,UPDATEandDELETEstatement – does that take time!