Should each and every table have a primary key?

后端 未结 15 728
甜味超标
甜味超标 2020-11-22 07:00

I\'m creating a database table and I don\'t have a logical primary key assigned to it. So, I\'m thinking about leaving it without a primary key, but I\'m feeling a bit guilt

相关标签:
15条回答
  • 2020-11-22 07:42

    It is a good practice to have a PK on every table, but it's not a MUST. Most probably you will need a unique index, and/or a clustered index (which is PK or not) depending on your need.

    Check out the Primary Keys and Clustered Indexes sections on Books Online (for SQL Server)

    "PRIMARY KEY constraints identify the column or set of columns that have values that uniquely identify a row in a table. No two rows in a table can have the same primary key value. You cannot enter NULL for any column in a primary key. We recommend using a small, integer column as a primary key. Each table should have a primary key. A column or combination of columns that qualify as a primary key value is referred to as a candidate key."

    But then check this out also: http://www.aisintl.com/case/primary_and_foreign_key.html

    0 讨论(0)
  • 2020-11-22 07:49

    Disagree with the suggested answer. The short answer is: NO.

    The purpose of the primary key is to uniquely identify a row on the table in order to form a relationship with another table. Traditionally, an auto-incremented integer value is used for this purpose, but there are variations to this.

    There are cases though, for example logging time-series data, where the existence of a such key is simply not needed and just takes up memory. Making a row unique is simply ...not required!

    A small example: Table A: LogData

    Columns:  DateAndTime, UserId, AttribA, AttribB, AttribC etc...
    

    No Primary Key needed.

    Table B: User

    Columns: Id, FirstName, LastName etc. 
    

    Primary Key (Id) needed in order to be used as a "foreign key" to LogData table.

    0 讨论(0)
  • 2020-11-22 07:49

    To make it future proof you really should. If you want to replicate it you'll need one. If you want to join it to another table your life (and that of the poor fools who have to maintain it next year) will be so much easier.

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