What's the best practice for primary keys in tables?

前端 未结 21 2175
别那么骄傲
别那么骄傲 2020-11-22 14:02

When designing tables, I\'ve developed a habit of having one column that is unique and that I make the primary key. This is achieved in three ways depending on requirements

相关标签:
21条回答
  • 2020-11-22 14:30

    I avoid using natural keys for one simple reason -- human error. Although natural unique identifiers are often available (SSN, VIN, Account Number, etc.), they require a human to enter them correctly. If you're using SSNs as a primary key, someone transposes a couple of numbers during data entry, and the error isn't discovered immediately, then you're faced with changing your primary key.

    My primary keys are all handled by the database program in the background and the user is never aware of them.

    0 讨论(0)
  • 2020-11-22 14:30

    I too always use a numeric ID column. In oracle I use number(18,0) for no real reason above number(12,0) (or whatever is an int rather than a long), maybe I just don't want to ever worry about getting a few billion rows in the db!

    I also include a created and modified column (type timestamp) for basic tracking, where it seems useful.

    I don't mind setting up unique constraints on other combinations of columns, but I really like my id, created, modified baseline requirements.

    0 讨论(0)
  • 2020-11-22 14:30

    GUIDs can be used as a primary key, but you need to create the right type of GUID so that it performs well.

    You need to generate COMB GUIDs. A good article about it and performance statistics is The Cost of GUIDs as Primary Keys.

    Also some code on building COMB GUIDs in SQL is in Uniqueidentifier vs identity(archive).

    0 讨论(0)
提交回复
热议问题