UNIQUE Index
In this page:
What is a Unique Index?
A UNIQUE index enforces that every value stored in the indexed column is different from every other row's value, rejecting any insert or update that would create a duplicate.
Example: What is a Unique Index?
CREATE TABLE users (id INT, email TEXT UNIQUE);
INSERT INTO users VALUES (1, '[email protected]');
-- Fails: duplicate email
INSERT INTO users VALUES (2, '[email protected]');
Creating UNIQUE Index during Table Creation
Defining a unique index at table-creation time bakes the constraint in from the very first row, which is the cleanest approach when you already know a column — like an email address — must never repeat.
Example: Creating UNIQUE Index during Table Creation
CREATE TABLE users (id INT, email TEXT, UNIQUE (email));
INSERT INTO users VALUES (1, '[email protected]');
Adding UNIQUE Index to Existing Tables
For a table that already exists and already has data, ALTER TABLE lets you add a unique index after the fact, though MySQL will refuse if the existing data already contains duplicate values.
Example: Adding UNIQUE Index to Existing Tables
CREATE TABLE users (id INT, email TEXT);
INSERT INTO users VALUES (1, '[email protected]');
ALTER TABLE users ADD UNIQUE (email);
Composite Unique Index
A composite unique index applies uniqueness to the combination of several columns together rather than each column alone — individual columns can repeat, but no two rows may share the exact same combination.
Example: Composite Unique Index
CREATE TABLE enrollments (student_id INT, course_id INT, UNIQUE (student_id, course_id));
INSERT INTO enrollments VALUES (1, 101);
-- Allowed: same student, different course
INSERT INTO enrollments VALUES (1, 102);
Dropping a Unique Index
Dropping a unique index removes the uniqueness enforcement along with the performance benefit, which means duplicate values become allowed in that column again going forward.
Example: Dropping a Unique Index
CREATE TABLE users (id INT, email TEXT, UNIQUE KEY uq_email (email));
ALTER TABLE users DROP INDEX uq_email;
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: