Alex Rivera | Logout

Should a database table always have primary keys?

Asked 2009-05-06T21:25:49.340
18

Should I always have a primary key in my database tables?

Let's take the SO tagging. You can see the tag in any revision, its likely to be in a tag_rev table with the postID and revision number. Would I need a PK for that?

Also since it is in a rev table and not currently use the tags should be a blob of tagIDs instead of multiple entries of multiple post_id tagid pair?

Edit
Report

1 Answer

3

I tend to agree that most tables should have a primary key. I can only think of two times where it doesn't make sense to do it.

  1. If you have a table that relates keys to other keys. For example, to relate a user_id to an answer_id, that table wouldn't need a primary key.
  2. A logging table, whose only real purpose is to create an audit trail.

Basically, if you are writing a table that may ever need to be referenced in a foreign key relationship then a primary key is important, and if you can't be positive it won't be, then just add the PK. :)

answered 2009-05-06T23:13:39.783

Your Answer