5

I'm in the process of learning Mysql, and I'm creating databases. So, after looking at several websites, the definition for a primary key is:

The PRIMARY KEY constraint uniquely identifies each record in a database table.

and is used like this:

    CREATE TABLE Persons
(
    P_Id int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Address varchar(255),
    City varchar(255),
    PRIMARY KEY (P_Id)          //primary key is on this line
)

However, I still don't know what it's used for and why we need it. So my question is.

Can someone explain to me what a primary key is (in basic english) and why we need one and what is it used for?

Thank-you.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
r1nzler
  • 2,533
  • 8
  • 28
  • 30
  • The only difficult part is... which other question is this a duplicate of? – p.campbell Mar 04 '12 at 00:30
  • possible duplicate of [What's the difference between Primary Key, Unique Key and Index in MySQL?](http://stackoverflow.com/questions/3844899/whats-the-difference-between-primary-key-unique-key-and-index-in-mysql) – p.campbell Mar 04 '12 at 00:33
  • Possible duplicate of [Difference between Key, Primary Key, Unique Key and Index in MySQL](https://stackoverflow.com/questions/3844899/difference-between-key-primary-key-unique-key-and-index-in-mysql) – philipxy Jun 07 '19 at 04:04

3 Answers3

6

A primary key is a column that is defined as uniquely identifying each row in a table.

Also, by defining a column as PRIMARY KEY, it may be referenced as a foreign key in other tables when defining referential integrity constraints.

Wolverine
  • 1,712
  • 1
  • 15
  • 18
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • +1 You may also find http://stackoverflow.com/questions/8038641/please-confirm-my-use-of-primary-key-and-unique-index/8038647#8038647 useful. – Michael Durrant Mar 04 '12 at 00:34
3

A primary key is a unique identifier for the row. It is normally automatically assigned by the database management system (if you specify auto-increment for that value). So if you have a database of people in an organisation, their primary key may be their employee number. Every time you add an employee, they receive a unique employee number that is usually the previous employees number + 1.

Without primary keys you could not distinguish between two employees called John Smith (without other information) Hope that is clear enough.

1

In simple words,

Primary Key = NOT NULL + UNIQUE

that means whichever column is assigned primary key, that column will neither take NULL values nor accept the duplicate values.