views:

40

answers:

3

Suppose I have a table Books with columns Book_ID (Primary Key), ISBN (Unique), and several others such as Title/author/etc.

I have another table Sales, with primary key Sale_ID, a foreign key to link to Books, and other fields with info on Sales. Sales only exist for books with ISBNs. Is it better database design to have Book_ID or ISBN be the primary key. Note: I will be LEFT JOINing Sales to Books on whichever the foreign key is chosen.

UPDATE: Some Books have no ISBN's because they're not published with them. However, I don't foresee (at least in the next several years) users being able to sell them, because I have no system for making sure that a given book w/o the ISBN isn't repeated.

A: 

I would always use your primary key

Nathan Koop
A: 

In general, I think I would go for the surrogate primary key book_id as the foreign key.

There are a few potential issues that I can identify if you were to use the non-primary key ISBN as a foreign key:

  • You might have a missing or unknown ISBN for a particular book. What would you do in case there is a sale of that book?
  • You might have an incorrect ISBN. To edit it, you would have to update all the tables that would be using it as a foreign key.
  • You might want to start selling books that don't have an ISBN in the future. Why are you storing books without an ISBN in the first place?
  • An index on book_id should be much more compact than one on an ISBN field.
Daniel Vassallo
Updated my question to with info on NULL ISBN Books.
babonk
A: 

I would always use ISBN. This way you have a simple way of enforcing your business rule, "Sales only exist for books with ISBNs" i.e. by making the ISBN column NOT NULL in the Sales table and referencing the ISBN column in the Books table.

I don't agree with @Daniel Vassallo that because you might want to start selling books that don't have an ISBN in the future you would want to drop the rule in the database today. There is a name for this design flaw: future creep. Also, the considerations of 'compact indexes' should always be secondary to those of basic data integrity.

onedaywhen
@onedaywhen: I think you're giving too much importance to this business rule. Why is the OP storing books without an ISBN in the first place? ... Mine wasn't a concrete, "always do this, never do that" answer. I only iterated a few potential issues that I could identify, if the OP were to use the `ISBN` as a foreign key (in fact, I updated my answer with a couple more points).
Daniel Vassallo