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

UNIQUE Constraint

Understanding UNIQUE

UNIQUE guarantees no two rows can share the same value in that column, which is the standard way to enforce things like one-email-per-account without relying on application-level checks alone.

Example: Understanding UNIQUE

sql
CREATE TABLE users (email VARCHAR(100) UNIQUE);

Duplicate Value Errors

Attempting to insert a value that already exists in a UNIQUE column causes MySQL to reject the entire insert and return a duplicate-key error rather than silently allowing the collision.

Example: Duplicate Value Errors

sql
CREATE TABLE users (email VARCHAR(100) UNIQUE);
INSERT INTO users VALUES ('[email protected]');
INSERT INTO users VALUES ('[email protected]'); -- duplicate-key error

Multiple Unique Columns

A table can carry several independent UNIQUE columns at once, and you can also combine multiple columns into a single composite UNIQUE constraint that only fires when the *combination* repeats.

Example: Multiple Unique Columns

sql
CREATE TABLE registrations (
  event_id INT,
  user_id INT,
  UNIQUE (event_id, user_id)
);

Adding UNIQUE to Existing Tables

Adding UNIQUE to an already-populated column via ALTER TABLE will fail immediately if any duplicate values already exist in the data, so cleanup usually has to happen first.

Example: Adding UNIQUE to Existing Tables

sql
ALTER TABLE users ADD UNIQUE (email);

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

Dropping UNIQUE Constraints

A UNIQUE constraint is implemented as an index behind the scenes, so removing it means dropping that index specifically — MySQL doesn't offer a separate unconstrain command.

Example: Dropping UNIQUE Constraints

sql
ALTER TABLE users DROP INDEX email;

⚠️ 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.