Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a PRIMARY KEY

In database code, I see references to a PRIMARY KEY. What is a PRIMARY KEY? and what difference does it make if some of the columns in one of my tables form a PRIMARY KEY... or don't form a PRIMARY KEY.

like image 833
Raedwald Avatar asked Oct 22 '25 02:10

Raedwald


2 Answers

1st Normal Form requires that you have a unique key for you to have a relation. If this requirement is not met (i.e. if you have no unique keys), then your table will be just a heap, not a relation.

The primary key is more or less (i.e. roughly speaking) one specially selected unique key. The one who designs the schema chooses it. The main difference between a PK and a unique key is that unique keys can contain NULL values while PKs cannot. Also, you can have more than one unique keys in a given table but at most one PK.

By making one of the unique keys a primary key, you allow other tables to easily point to this table via their foreign keys (FKs). Technically the FKs (of the child tables) can also point to any unique key (from the parent table) but usually people use for that purpose the primary key (PK) which (as said) is basically just one of the unique keys. That means FKs usually point to PKs.

For more details, see also:

What is the difference b/w Primary Key and Unique Key

like image 51
peter.petrov Avatar answered Oct 25 '25 01:10

peter.petrov


A primary key is a key in a relational database that is unique for each record.

If a reference to a column in a database is primary key, then that value will be unique. when you try to add another row to the value with the same primary key, it throws an error.

If you dont have a primary key on a column, you can add any non-unique values as well.

like image 21
alekya reddy Avatar answered Oct 25 '25 00:10

alekya reddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!