Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

True or False: Good design calls for every table to have a primary key, if nothing else, a running integer

Consider a grocery store scenario (I'm making this up) where you have FACT records that represent a sale transaction, where the columns of the Fact table include

SaleItemFact Table
------------------
CustomerID  
ProductID  
Price  
DistributorID  
DateOfSale  
Etc  
Etc  
Etc  

Even if there are duplicates in the table when you consider ALL the keys, I would contend that a surrogate running numeric key (i.e. identity column) should be made up, e.g., TransactionNumber of type Integer.

I can see someone arguing that a Fact table might not have a unique key (though I'd invent one and waste the 4 bytes, but how about a dimension table?

like image 698
Chad Avatar asked Mar 06 '10 00:03

Chad


People also ask

Is it necessary to have a primary key in every table?

Every table can have (but does not have to have) a primary key. The column or columns defined as the primary key ensure uniqueness in the table; no two rows can have the same key. The primary key of one table may also help to identify records in other tables, and be part of the second table's primary key.

Is primary key always integer?

No, the primary key does not have to be an integer; it's just very common that it is. As an example, we have User ID's here that can have leading zeroes and so must be stored in a varchar field. That field is used as a primary key in our Employee table.

Can I create a table without primary key?

The data columns in your table might not need a primary key. To replicate tables that do not have primary keys, you can specify a unique index or add the ERKEY shadow columns.

Is it always necessary to have a primary key in any relation what happens if we don't explicitly declare a primary key while creating the table schema?

No, it is not required for every table to have a primary key. Whether or not a table should have a primary key is based on requirements of your database. Even though this is allowed it is bad practice because it allows for one to add duplicate rows further preventing the unique identification of rows.


2 Answers

First normal form requires a primary key on every table. So this is the bare minimum required for good database design. What you choose for the primary key is open to much debate. But first normal form for database design is not.

like image 122
Randy Minder Avatar answered Oct 03 '22 15:10

Randy Minder


One reason, among many, to have a unique key per row (built from the data, or otherwise) is to facilitate updates or deletions to that specific row.

In any case, this question is kind of silly, because there really isn't an engineering trade-off at stake. There is no real proposed benefit to not having the key, so what's the point? True/yes, rows should have unique identifiers.

like image 41
wsorenson Avatar answered Oct 03 '22 13:10

wsorenson