Should each and every table have a primary key?

后端 未结 15 1001
甜味超标
甜味超标 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: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.

提交回复
热议问题