MySQL — Primary Key
Basic Primary Key
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL
);
Named Primary Key
CREATE TABLE employees (
id INT,
name VARCHAR(100) NOT NULL,
CONSTRAINT pk_employees PRIMARY KEY (id)
);
Composite Primary Key
CREATE TABLE enrollments (
student_id INT,
course_id INT,
enrolled_date DATE,
PRIMARY KEY (student_id, course_id)
);
Adding Primary Key After Creation
ALTER TABLE employees ADD PRIMARY KEY (id);
-- or with a name
ALTER TABLE employees ADD CONSTRAINT pk_emp PRIMARY KEY (id);
Dropping Primary Key
ALTER TABLE employees DROP PRIMARY KEY;
Auto-Increment Primary Key
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
Primary Key Rules
| Rule | Description |
|---|---|
| Unique | No two rows can share the same value |
| Not Null | Cannot be NULL |
| One per table | Only one primary key allowed |
| Indexed | Automatically creates an index |
Mini Practice
Write SQL code that:
- Creates a table with a single-column primary key
- Creates a composite primary key
- Adds a primary key to an existing table
- Uses AUTO_INCREMENT with a primary key
Up Next
Continue with Foreign Key — linking tables together.
Related Topics
Frequently Asked Questions about Primary Key
What is Primary Key in MySQL?
Primary Key is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Primary Key?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Primary Key.
Why is Primary Key important in MySQL?
Primary Key is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.