Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a primary key necessary? [duplicate]

Tags:

sql

mysql

In database systems, should every table have a primary key?

For example I have a table table1(foreignkey1,foreignkey2,attribute) like this.table1 does not have a primary key.

Should I define a primary key for this table like table1id?

like image 645
user2556081 Avatar asked Dec 19 '15 14:12

user2556081


People also ask

Can primary keys be duplicates?

You can define keys which allow duplicate values. However, do not allow duplicates on primary keys as the value of a record's primary key must be unique.

Is it mandatory to have a primary key?

Every table can have (but does not have to have) a primary key. The column or columns defined as the primary key ensure uniqueness in the table; no two rows can have the same key.

Is primary key does not allow duplicate values?

A primary key is a column of table which uniquely identifies each tuple (row) in that table. Primary key enforces integrity constraints to the table. Only one primary key is allowed to use in a table. The primary key does not accept the any duplicate and NULL values.

Should there be only one primary key?

A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key. If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s).


1 Answers

This is a subjective question, so I hope you don't mind me answering with some opinion :)

In the vast majority of tables I've made – I'm talking 95%+ – I've added a primary key, and been glad I did. This is either the most critical unique field in my table (think "social security number") or, more often than not, just an auto-incrementing number that allows me to quickly and easily refer to a field when querying.

This latter use is the most common, and it even has its own name: a "surrogate" or "synthetic" key. This is a value auto-generated by the database and not derived from your application data. If you want to add relations between your tables, this surrogate key is immediately helpful as a foreign key. As someone else answered, these keys are so common that MySQL likes to add one even if you don't, so I'd suggest that means the consensus is very heavily biased towards adding primary keys.

One other thing I like about primary keys is that they help convey your intent to others reading your table schemata and also to your DMBS: "this bit is how I intend to identify my rows uniquely, don't let me try to break that rule!"

To answer your question specifically: no, a primary key is not necessary. But realistically if you intend to store data in the table for any period of time beyond a few minutes, I would very strongly recommend you add one.

like image 101
TwoStraws Avatar answered Oct 03 '22 13:10

TwoStraws