← Back to MySQL Course | Chapter 4: Constraints | Lesson 4 of 8

PRIMARY KEY

Understanding PRIMARY KEY

A PRIMARY KEY uniquely identifies every row in a table and, unlike a plain UNIQUE column, can never contain NULL — it's the anchor MySQL and your application both rely on to reference a specific record unambiguously.

Example: Understanding PRIMARY KEY

sql
CREATE TABLE users (id INT PRIMARY KEY);

Composite Primary Keys

A composite primary key spans two or more columns together, used when no single column is unique on its own — a classic example is an order_items table keyed on (order_id, product_id) combined.

Example: Composite Primary Keys

sql
CREATE TABLE order_items (
  order_id INT,
  product_id INT,
  PRIMARY KEY (order_id, product_id)
);

Adding PRIMARY KEY to Existing Tables

Adding a primary key to an existing table via ALTER TABLE requires that the target column already contains no NULLs and no duplicate values, or the operation fails outright.

Example: Adding PRIMARY KEY to Existing Tables

sql
ALTER TABLE users ADD PRIMARY KEY (id);

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Dropping a PRIMARY KEY

Because a table can only ever have one primary key, dropping it doesn't require naming the column — MySQL already knows exactly which constraint you mean.

Example: Dropping a PRIMARY KEY

sql
ALTER TABLE users DROP PRIMARY KEY;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Best Practices for Primary Keys

Nearly every well-designed table should have a primary key: it speeds up lookups and joins dramatically and gives every row a stable, unambiguous identity to reference from other tables.

Example: Best Practices for Primary Keys

sql
CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(100)
);

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.