Lesson 33 of 60 – PRIMARY KEY
55%

PRIMARY KEY in SQL

A PRIMARY KEY is a constraint used to uniquely identify each record in a table. A primary key value must be unique and cannot contain NULL values.

Note: A table normally has one primary key constraint, and that key can consist of one column or multiple columns.

1. What is a PRIMARY KEY?

A PRIMARY KEY uniquely identifies every record in a table.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100)
);

Here, student_id uniquely identifies each student.

2. Why is PRIMARY KEY Important?

A primary key helps the database identify records accurately.

  • Identifies each record uniquely
  • Prevents duplicate key values
  • Does not allow NULL values
  • Helps establish relationships between tables
  • Can be used to find a specific record

3. PRIMARY KEY Syntax

The basic column-level syntax is:

column_name data_type PRIMARY KEY

Example:

student_id INT PRIMARY KEY

4. PRIMARY KEY During CREATE TABLE

You can define a primary key while creating a table.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100),
    age INT
);

The student_id column becomes the primary key.

5. PRIMARY KEY Values Must Be Unique

Two records cannot have the same primary key value.

student_id
101
102
103

Each value uniquely identifies a record.

This would create a duplicate key:

101
101

6. PRIMARY KEY Cannot Be NULL

A primary key cannot contain NULL values.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100)
);

Every student record must have a valid student_id.

7. PRIMARY KEY with INT

An integer column is commonly used as a primary key.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100)
);

Integer IDs are commonly used because they are simple and efficient identifiers.

8. PRIMARY KEY with VARCHAR

A text column can also be used as a primary key if its values are unique.

CREATE TABLE users (
    username VARCHAR(50) PRIMARY KEY,
    name VARCHAR(100)
);

Each username must be unique.

9. Insert Data Using PRIMARY KEY

When inserting data, provide a unique primary key value.

INSERT INTO students (student_id, name)
VALUES (101, 'Rahul');

Another record can use a different ID:

INSERT INTO students (student_id, name)
VALUES (102, 'Amit');

10. Duplicate PRIMARY KEY Error

If you try to insert a duplicate primary key value, the database will reject it.

INSERT INTO students (student_id, name)
VALUES (101, 'Ravi');

If student_id 101 already exists, this insert causes a duplicate key error.

11. PRIMARY KEY with AUTO_INCREMENT

In MySQL, AUTO_INCREMENT can generate numeric primary key values automatically.

CREATE TABLE students (
    student_id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100)
);

The database can generate the student_id when new records are inserted.

12. INSERT with AUTO_INCREMENT

When AUTO_INCREMENT is used, you can omit the ID during INSERT.

INSERT INTO students (name)
VALUES ('Rahul');

MySQL generates the primary key value automatically.

13. PRIMARY KEY with SELECT

The primary key can be used to find a specific record.

SELECT *
FROM students
WHERE student_id = 101;

This searches for the student whose primary key is 101.

14. PRIMARY KEY with UPDATE

A primary key is commonly used to identify the record that should be updated.

UPDATE students
SET name = 'Rahul Kumar'
WHERE student_id = 101;

The record with student_id 101 is updated.

15. PRIMARY KEY with DELETE

You can use the primary key to delete a specific record.

DELETE FROM students
WHERE student_id = 101;

Only the record with student_id 101 is targeted.

16. Table-Level PRIMARY KEY

A primary key can also be defined at the table level.

CREATE TABLE students (
    student_id INT,
    name VARCHAR(100),
    PRIMARY KEY (student_id)
);

Here, the primary key is defined separately from the column definition.

17. Named PRIMARY KEY Constraint

You can give a primary key constraint a name.

CREATE TABLE students (
    student_id INT,
    name VARCHAR(100),
    CONSTRAINT pk_students
    PRIMARY KEY (student_id)
);

The constraint is named pk_students.

18. Add PRIMARY KEY with ALTER TABLE

You can add a primary key to an existing table.

ALTER TABLE students
ADD PRIMARY KEY (student_id);

The student_id column becomes the primary key.

19. Add Named PRIMARY KEY with ALTER TABLE

You can add a named primary key constraint to an existing table.

ALTER TABLE students
ADD CONSTRAINT pk_students
PRIMARY KEY (student_id);

The primary key constraint is given the name pk_students.

20. Composite PRIMARY KEY

A composite primary key uses two or more columns together to uniquely identify a record.

CREATE TABLE enrollments (
    student_id INT,
    course_id INT,
    PRIMARY KEY (student_id, course_id)
);

The combination of student_id and course_id must be unique.

21. Example of Composite PRIMARY KEY

Suppose a student can enroll in multiple courses.

student_id | course_id
101        | 1
101        | 2
102        | 1

Here, the combination of student_id and course_id identifies each enrollment.

22. PRIMARY KEY and FOREIGN KEY

A primary key in one table can be referenced by a foreign key in another table.

CREATE TABLE courses (
    course_id INT PRIMARY KEY,
    course_name VARCHAR(100)
);

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
);

The courses table provides the referenced primary key.

23. One PRIMARY KEY Constraint

A table has one primary key constraint, although that primary key can contain multiple columns.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100)
);

You cannot define separate independent primary key constraints for different columns in the same table.

24. Dropping a PRIMARY KEY

You can remove a primary key constraint using ALTER TABLE.

ALTER TABLE students
DROP PRIMARY KEY;

In MySQL, this removes the primary key constraint from the table.

25. PRIMARY KEY vs UNIQUE

Both PRIMARY KEY and UNIQUE can enforce uniqueness, but they are not identical.

  • PRIMARY KEY uniquely identifies records.
  • A table has one primary key constraint.
  • Primary key values cannot be NULL.
  • UNIQUE is used to prevent duplicate values in a column or combination of columns.
  • A table can have multiple UNIQUE constraints.

26. Common PRIMARY KEY Mistake

A common mistake is trying to create a primary key on a column containing duplicate values.

ALTER TABLE students
ADD PRIMARY KEY (student_id);

If duplicate student_id values already exist, the database may reject the operation.

Tip: Check for duplicate values before adding a primary key to an existing table.

27. Check the PRIMARY KEY

In MySQL, you can use SHOW CREATE TABLE to inspect the table definition.

SHOW CREATE TABLE students;

This can help you check the primary key and other table definitions.

28. Practical PRIMARY KEY Example

Consider a student table where every student needs a unique ID.

CREATE TABLE students (
    student_id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    mobile VARCHAR(15)
);

The student_id uniquely identifies each student and can be generated automatically.

29. PRIMARY KEY in a Real Project

In a student management system, student_id can be used as the primary key.

CREATE TABLE students (
    student_id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) UNIQUE,
    course_id INT
);

Other tables can use student_id as a reference when relationships are required.

30. Complete PRIMARY KEY Example

Here is a complete example using a primary key and a related foreign key.

CREATE TABLE courses (
    course_id INT PRIMARY KEY AUTO_INCREMENT,
    course_name VARCHAR(100) NOT NULL
);

CREATE TABLE students (
    student_id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
);

INSERT INTO courses (course_name)
VALUES ('Python');

INSERT INTO students (name, course_id)
VALUES ('Rahul', 1);

Here, both tables have their own primary keys, and the students table uses course_id as a foreign key.

📌 Key Points

  • PRIMARY KEY uniquely identifies each record.
  • Primary key values must be unique.
  • A primary key cannot contain NULL values.
  • A table has one primary key constraint.
  • A primary key can contain one or multiple columns.
  • A composite primary key contains multiple columns.
  • PRIMARY KEY can be used with AUTO_INCREMENT in MySQL.
  • Primary keys are commonly referenced by FOREIGN KEY constraints.
  • You can add or remove a primary key using ALTER TABLE.
  • PRIMARY KEY and UNIQUE are different constraints.

🧠 Quick Quiz

Question: What is the main purpose of a PRIMARY KEY?