MYSQL - What is a primary key?
Asked Answered
D

3

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.

Deltoid answered 4/3, 2012 at 0:28 Comment(3)
The only difficult part is... which other question is this a duplicate of?Kenward
possible duplicate of What's the difference between Primary Key, Unique Key and Index in MySQL?Kenward
Possible duplicate of Difference between Key, Primary Key, Unique Key and Index in MySQLRaising
I
5

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.

Indication answered 4/3, 2012 at 0:31 Comment(1)
+1 You may also find #8039141 useful.Ivaivah
C
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.

Chaparro answered 4/3, 2012 at 0:33 Comment(3)
I'd say 'sometimes assigned by the dbms' rather than 'normally', but otherwise agree.Fortification
Okay, fair call, I was being picky. Not meaning to start a fight.Fortification
@RichardA I would imagine "normal" is the norm these days (just as is not having a [real] DBA involved at any level...)Depressomotor
G
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.

Giroux answered 27/2, 2021 at 12:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.