简体   繁体   中英

No primary key, or surrogate key?

I'm about to create a table which will hold a customer ID (GUID), a data point (string) and the time of entry. However, I can't figure out how to best key it. I cannot guarantee that the 3-tuple Id/string/time is unique (the table will contain user input, and we foresee that some users will try to script form submissions, therefore the time might not have sufficient resolution).

We will do lookups in this table quite often, so query speed is important. On the other hand, inserts can't be totally crippled either.

So, I see two choices: Either go without a primary key, or define a surrogate auto-increment key. What would be the best given the above requirements? Could I use a surrogate key and a non-unique index for the three data columns?

We're using SQL Server 2008 R2.

So what does a table that has rows like this mean?

customer_id                           data_point     time_entered
--
6F9619FF-8B86-D011-B42D-00C04FC964FF  some data      2011-11-23 10:02:12.34567
6F9619FF-8B86-D011-B42D-00C04FC964FF  some data      2011-11-23 10:02:12.34567
6F9619FF-8B86-D011-B42D-00C04FC964FF  some data      2011-11-23 10:02:12.34567

And what does a table that has rows like this mean?

id  customer_id                           data_point     time_entered
--
1   6F9619FF-8B86-D011-B42D-00C04FC964FF  some data      2011-11-23 10:02:12.34567
2   6F9619FF-8B86-D011-B42D-00C04FC964FF  some data      2011-11-23 10:02:12.34567
3   6F9619FF-8B86-D011-B42D-00C04FC964FF  some data      2011-11-23 10:02:12.34567

If you don't have a good answer to the first question before you hang an id number on that table, you won't have a good answer afterwards, either.

Unless you have good reason to do otherwise, default your database design to use a surrogate primary key using a smallint/int/bigint as appropriate with the IDENTITY property set so that it will generate automatically created primary key values. If you decide later on that you want to enforce a natural key using one or more columns in the table, you can do so by creating a UNIQUE CONSTRAINT.

Although you can have none, one or many unique constraints on a table, you can only have one primary key, so use it as a surrogate primary key and avoid a lot of other problems in so doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM