Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should every table have a primary key?

Tags:

sql

database

I read somewhere saying that every table should have a primary key to fulfill 1NF.

I have a tbl_friendship table.

There are 2 fields in the table : Owner and Friend.

Fields of Owner and Friends are foreign keys of auto increment id field in tbl_user.

Should this tbl_friendship has a primary key? Should I create an auto increment id field in tbl_friendship and make it as primary key?

like image 516
zac1987 Avatar asked Aug 15 '11 12:08

zac1987


People also ask

Is it necessary to have primary key in table in SQL?

Each database table needs a primary key because it ensures row-level accessibility. If you choose an appropriate primary key, you can specify a primary key value, which lets you query each table row individually and modify each row without altering other rows in the same table.

Can a table created without primary key?

Table does not have to have primary key.


1 Answers

Primary keys can apply to multiple columns! In your example, the primary key should be on both columns, For example (Owner, Friend). Especially when Owner and Friend are foreign keys to a users table rather than actual names say (personally, my identity columns use the "Id" naming convention and so I would have (OwnerId, FriendId)

Personally I believe every table should have a primary key, but you'll find others who disagree.

Here's an article I wrote on the topic of normal forms. http://michaeljswart.com/2011/01/ridiculously-unnormalized-database-schemas-part-zero/

like image 84
Michael J Swart Avatar answered Oct 04 '22 01:10

Michael J Swart