Using generated numbers for primary keys

Using generated numbers for primary keys

What are the advantages and disadvantages of using sequentially generated numbers or randomly generated numbers for primary database keys?

    Requires Free Membership to View

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

Was the intent of your question to distinguish the pros and cons of sequential versus random numbers? Sequential numbers never repeat, and you won't run into trouble until the next number is larger than the column can hold, which is usually not a problem unless you define the column as tinyint or something. Random numbers might repeat since they are only really pseudo-random, but I wouldn't worry about it, because, again, you're probably not going to have a table large enough for this to occur. Random numbers also have the advantage that you won't be tempted to try SELECT MAX(ID) in order to get back the key of the latest inserted record -- but that's a different discussion.

It's more likely that you're interested in the advantages and disadvantages of a surrogate key as compared to a natural or "real" primary key.

Key Advantages Disadvantages
natural
  • self-identifying
  • bulky
  • may repeat
  • may be null
  • may change
surrogate
  • lightweight
  • unique
  • not null
  • never changes
  • meaningless

As you may be able to tell from the above, the advantages of one are the disadvantages of the other.

This answer is continued.


This was first published in June 2002

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.