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

MySQL — Unique

Basic Unique Constraint

CREATE TABLE users (
    id INT PRIMARY KEY,
    email VARCHAR(255) UNIQUE,
    username VARCHAR(50) UNIQUE
);

Named Unique Constraint

CREATE TABLE users (
    id INT PRIMARY KEY,
    email VARCHAR(255),
    CONSTRAINT uq_email UNIQUE (email)
);

Composite Unique

CREATE TABLE enrollments (
    student_id INT,
    semester VARCHAR(20),
    CONSTRAINT uq_enrollment UNIQUE (student_id, semester)
);

Adding Unique After Creation

ALTER TABLE users ADD UNIQUE (email);
-- or with a name
ALTER TABLE users ADD CONSTRAINT uq_email UNIQUE (email);

Dropping Unique

ALTER TABLE users DROP INDEX uq_email;

UNIQUE vs PRIMARY KEY

FeatureUNIQUEPRIMARY KEY
NULLs allowedYes (one per column)No
Count per tableMultipleOne
Auto-indexedYesYes

Viewing Unique Constraints

SHOW INDEX FROM users WHERE Non_unique = 0;

Mini Practice

Write SQL code that:

  1. Creates a table with a UNIQUE constraint
  2. Creates a composite UNIQUE constraint
  3. Adds UNIQUE to an existing column
  4. Drops a UNIQUE constraint

Up Next

Continue with Check — validating column values with conditions.

Related Topics

Frequently Asked Questions about Unique

What is Unique in MySQL?

Unique 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 Unique?

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 Unique.

Why is Unique important in MySQL?

Unique is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.