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

UNIQUE Constraint

UNIQUE is like a rule that no two students in class may have the same locker number. It keeps a value from repeating.
Syntax
sql
column_name datatype UNIQUE

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.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Assuming UNIQUE prevents multiple NULL values, when MySQL allows several NULL values in a unique column.
  2. Adding UNIQUE to a column that already has duplicate values, which fails.
  3. Expecting two separate UNIQUE columns to be unique together, when a combined rule needs UNIQUE (a, b).
🔒

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.