MySQL PRIMARY KEY Constraint

Primary key identifies each table row

A PRIMARY KEY uniquely identifies each row in a table. Primary-key columns are unique and cannot contain NULL. A table can have only one primary key, although that key can contain more than one column.

CREATE TABLE student (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    class VARCHAR(20) NOT NULL,
    mark TINYINT UNSIGNED NOT NULL DEFAULT 0,
    gender VARCHAR(10) NOT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB
  DEFAULT CHARSET=utf8mb4;
Creating and deleting PRIMARY KEY constraints in MySQL

Where this fits: CREATE TABLE defines columns; a PRIMARY KEY ensures each row has a unique identifier; INSERT and SELECT then work with those rows.

On this page — Show page sectionsHide page sections

Create a Primary Key with the Table

Defining the key at table creation time is normally the clearest approach:

CREATE TABLE student (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB;

Add a Primary Key to an Existing Table

This ALTER statement is for a table that does not already have a PRIMARY KEY. The student table created in the example above already has one, so do not execute both examples on that same table.

ALTER TABLE student
ADD PRIMARY KEY (id);

The existing column values must satisfy the key rules: no duplicates and no NULL values.

Composite Primary Key

For a standalone example, first create an enrollment table with no primary key; then run the ALTER statement below. A pair of student/course IDs can identify a unique enrollment:

CREATE TABLE enrollment (
    student_id INT UNSIGNED NOT NULL,
    course_id INT UNSIGNED NOT NULL,
    enrolled_on DATE NOT NULL
);

A primary key can use more than one column when the combination uniquely identifies a row:

ALTER TABLE enrollment
ADD PRIMARY KEY (student_id, course_id);

Drop a Primary Key

Be careful with the student example: its AUTO_INCREMENT ID must remain indexed. A simple DROP PRIMARY KEY can fail without first making an appropriate key/index change. Never try this on production data without checking dependencies.

ALTER TABLE student
DROP PRIMARY KEY;
Changing a primary key can affect foreign keys, indexes and application code. Review dependencies before altering a production table.

Primary Key vs UNIQUE

PropertyPRIMARY KEYUNIQUE
Rows identified uniquelyYesYes
NULL allowedNoYes, when the column is nullable
How many per table?One primary keyMultiple UNIQUE indexes can exist
InnoDB organizationUsed as the clustered indexSecondary unique index unless it is chosen as the clustered key in special cases

For InnoDB, secondary-index entries also contain the primary-key columns, so a short primary key is usually preferable.

Inspect Keys and Constraints

SHOW CREATE TABLE student;
SHOW INDEX FROM student;

You can also query INFORMATION_SCHEMA when you need metadata across many tables.

Duplicate Primary-Key Values and INSERT IGNORE

A normal insert that violates a primary key produces an error:

INSERT INTO student (id, name, class, mark, gender) VALUES
(10, 'Test name', 'Four', 55, 'male'),
(36, 'Test name 2', 'Four', 57, 'male');

MySQL supports INSERT IGNORE, which can convert certain errors, including duplicate-key violations, into warnings so processing can continue:

INSERT IGNORE INTO student (id, name, class, mark, gender) VALUES
(10, 'Test name', 'Four', 55, 'male'),
(36, 'Test name 2', 'Four', 57, 'male');
IGNORE should not be used merely to hide data-quality problems. Check warnings and understand which rows were accepted or skipped.

Example: Student ID and Phone Number

Primary key and unique phone-number example

A student ID is a natural primary key candidate because every row requires one unique identifier. A phone-number column may instead use a UNIQUE constraint while remaining nullable when a student has not supplied a number.

Back to top ↑




Subscribe to our YouTube Channel here



plus2net.com




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer