Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server primary key on datetime field

I'm creating a new table in SQL Server 2005 that needs 2 fields: DateTime and MyValue (Int32). The DateTime field will be unique so I will be setting a unique constraint on it.

Which table structure is better and why?

MyIndex (PK, int)
MyDate (datetime) (IX_UniqueKey)
MyValue (int)

or

MyDate (PK, datetime)
MyValue (int)

My feeling is that I don't want an artificial PK (MyIndex) in this table because it is unnecessary and because the dates will be unique I will use them to access any record. However, it may be that it's more performant to have an artificial PK...?

like image 470
Guy Avatar asked Mar 06 '10 03:03

Guy


People also ask

Can a date be part of a composite primary key?

The primary key is composite made up of the date in which the part price is being modified, and a foreign key to the Part's unique ID on the Parts Table.

What is PKEY in SQL?

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).


1 Answers

When you say the dates will be unique, do you mean you think they will be unique, or their uniqueness is guaranteed by the statement of the problem? In my experience, some things turn out to be a good deal less unique than one imagines (US social security numbers being an example).

If the date values are not guaranteed unique, you should add the integer key.

If the date values are guaranteed unique, do they change? If they do change, are they referenced by other tables? If both answers are "yes" you probably should add the integer key.

If the date values are guaranteed unique, and don't change or are not referenced, you can use them for the key. Regular DATETIMEs are 8 bytes and standard INTEGER values are 4 bytes which might have a minor effect on indexing. If your date values are just dates, or only exact to the minute or less, and in the more restricted range allowed by the type, you can use SMALLDATETIME and get those index values down to 4 bytes.

like image 55
Larry Lustig Avatar answered Nov 23 '22 18:11

Larry Lustig