Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: Clustered index on datetime, ASC or DESC

Tags:

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.

like image 241
Eyvind Avatar asked Jun 25 '09 14:06

Eyvind


People also ask

Which column should be assigned a clustered index?

The clustered index should go on the column that will be the most queried. This includes joins, as a join must access the table just like a direct query, and find the rows indicated.

Does order matter for clustered index?

You should order your composite clustered index with the most selective column first. This means the column with the most distinct values compared to total row count.

Which of the following can be used to create an index on a table?

The CREATE INDEX statement is used to create indexes in tables.

What is the correct syntax for creating an index?

The syntax to create an index in SQL is: CREATE [UNIQUE] INDEX index_name ON table_name (column1, column2, ... column_n); UNIQUE.


1 Answers

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.

like image 166
marc_s Avatar answered Sep 17 '22 15:09

marc_s