views:

1274

answers:

1

If I have an SQL Server table with a clustered index on a datetime field, that is set to DateTime.Now (from C#) before inserts, should the index be ascending or descending to avoid reorganization of the table?

Thanks.

+8  A: 

Doesn't really matter - but is the DateTime really guaranteed to be unique?? I would AVOID putting a clustered index on just a DateTime - I would use a INT IDENTITY or BIGINT IDENTITY instead, and put a regular non-clustered index on DateTime (since that's really not guaranteed to be unique......)

Marc

PS: Like a primary key, the general consensus on what a clustered key should be is:

  • unique (otherwise SQL Server will "uniquify" it by adding a 4-byte uniqueifier to it)
  • as narrow as possible
  • static (never change)
  • ever increasing

The column(s) that make up the clustered key (including that 4-byte uniqueifier) are added to EVERY ENTRY in EVERY non-clustered index - so you want to keep those as slim as possible.

PS 2: the clustering key(s) are added to each non-clustered index because that's the way that SQL Server will retrieve the whole rows once it's found the search value in the non-clustered index. It's the row's "location" in the database, so to speak. Therefore, it should be unique and narrow.

marc_s
So a clustered index needs to be unique?
Eyvind
If it's *NOT* unique, then SQL Server will automagically add a 4-byte "uniqueifier" - if ever possible, try to avoid that!
marc_s
Thanks, didn't know that. So, given that the table in question has a PK that is a uniqueidentifier, would it be better to create the clustered index on the datetime field AND the PK?
Eyvind
OH GOD NO!! The PK is a GUID = 16 Byte, and the DATETIME is another 8 BYTE - I would really just insert a INT IDENTITY(1,1) (4-byte) and be done with it!
marc_s
Also, GUID's make for very bad performance when used as clustering keys, since they're by nature totally random. This causes lots of index fragmentation and poor performance as a rule of thumb. Avoid GUID's in clustered indices!
marc_s
don't forget that your clustered key is stored in every row of every index for that table as the pointer back to the clustered index. So, the bigger your clustered index, the bigger (and slower) your non-clustered indexes will all be.
Scott Ivey