views:

143

answers:

3

Example table:

CREATE TABLE Log (
    logID    int identity
    logDate  datetime
    logText  varchar(42)
)

logID is already indexed because it is a primary key, but if you were to query this table you would likely want to use logDate as a constraint. However, both logID and logDate are going to be in the same order because logDate would always be set to GETDATE().

Does it make sense to put an extra non-clustered index on logDate, taking into account that for the Log table it is important to have fast writes.

+3  A: 

If you'll have lots of query with a

WHILE LogDate > ......

(or something similar) clause - yes, by all means!

The clustered index on the LogID will not help if you select by date - so if that's a common operation, a non-clustered index on the date will definitely help a lot.

Marc

marc_s
Or, indeed, make the index on LogDate be the clustered index, if it's going to be the primary means of locating rows
Damien_The_Unbeliever
Given the accuracy of datetime the clustered index is unlikely to be unique if it is on LogDate alone, SQL will be forced to add a 4 byte uniquifier which will be a waste given the LogId could be added at the same cost.
Andrew
+5  A: 

Make a clustered index logDate, logID (in that order). As datetime is "growing" this should not cost anything extra. logID saves you from inserting two logentries at the same time (could happen)

Arthur
How do you implement something like this? Do you declare both columns as the primary key or skip the PK and create the index with a unique check on logID?
SurroundedByFish
1) Leave logID as your primary key (this alone is not an index). 2) Delete the current clustered index on logID3) Create an clustered Index on logDate, logID4) eventually create an unique index on logID (if you need access logID)
Arthur
I could not create a clustered index when a PK had already auto-created one and I also could not drop the index while the PK existed. However, I did get it to work by creating the index for both coluns before adding the PK constraint on the ID.
SurroundedByFish
A: 

Arthur is spot on with as considering the clustered index on logdate, logid since you will potentialy run into duplicates within the window of the datetime accuracy (3.33ms on SQL 2005).

I would also consider in advance whether the table is going to be large and should use table partitioning to allow the log to have a sliding window and old data removed without the need for long running delete statements. That all depends on the quantity of log records and whether you have enterprise edition.

Andrew