Understanding Primary Key in SQL: Easy Tutorial for Students and Beginners

A Primary Key is a column (or set of columns) in a table that uniquely identifies each row.

Think of it like your Aadhar Number or Roll Number in college:

  • Every person/student has a unique number.
  • No two people can have the same Aadhar or roll number.
  • It can’t be empty (everyone must have one).

That’s exactly how a primary key works in SQL.

Rules of Primary Key

  1. Unique → No two rows can have the same primary key.
  2. Not NULL → You cannot leave it blank.
  3. Each table can have only one primary key.
    (But that key can include one or more columns – called a composite key).

Example in MySQL
Table without primary key:

sql

CREATE TABLE students (
    id INT,
    name VARCHAR(50),
    class VARCHAR(20)
);

Here, nothing stops two students from having the same id.

You could insert:

idnameclass
1RameshScience
1PriyaArts

Problem: Both have the same id, so we can’t tell who is who.

Table with Primary Key:

sql

CREATE TABLE students (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    class VARCHAR(20)
);

Now:

  • Each id must be unique.
  • You can’t leave id empty.

So if you try to insert two rows with the same id, MySQL will give an error.

Real-Life Analogy

  • Primary Key = Roll Number in college
    • Every student has a unique roll number.
    • Two students cannot share the same roll number.
    • A roll number cannot be empty.

Other examples:

  • Bank Account Number
  • Vehicle Registration Number
  • Mobile SIM Number

Just remember:

Primary Key = Identity Card of the row

Unique ✔

Must exist (NOT NULL) ✔

Only one per table ✔