MySQL PRIMARY KEY Constraint

Introduction

A PRIMARY KEY constraint uniquely identifies each record in a table.

Every table should have a primary key to ensure that each row can be uniquely identified.


Characteristics of Primary Key

A primary key has two main properties:

  • Values must be unique

  • Values cannot be NULL

This ensures every record in the table can be uniquely identified.


Example

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

In this example, the id column uniquely identifies each student.


Auto Increment Primary Key

Often, primary keys are created with AUTO_INCREMENT so values increase automatically.

Example:

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

Composite Primary Key

A table can also have a composite primary key, which uses multiple columns.

Example:

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

Key PointsThe primary

  • Your key uniquely identifies each record

  • Cannot contain duplicate values

  • Cannot contain NULL values

  • Each table can have only one primary key