</>
Skip to content
MySQL lessons (35/48)

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

RuleDescription
UniqueNo two rows can share the same value
Not NullCannot be NULL
One per tableOnly one primary key allowed
IndexedAutomatically creates an index

Mini Practice

Write SQL code that:

  1. Creates a table with a single-column primary key
  2. Creates a composite primary key
  3. Adds a primary key to an existing table
  4. 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.