Advertisement

Google Ad Slot: content-top

MySQL UNIQUE


MySQL UNIQUE Constraint

The UNIQUE constraint in MySQL ensures that all values in a column or a set of columns are distinct (no duplicates). It is commonly used to prevent duplicate data in database tables.


PRIMARY KEY constraint automatically has a UNIQUE constraint.

However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

UNIQUE Constraint on CREATE TABLE


Example
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
phone_number VARCHAR(15),
CONSTRAINT unique_phone UNIQUE (phone_number)
);

Explanation:

  • email → Ensures no two students have the same email.
  • phone_number → Named unique_phone to ensure phone numbers are unique.


You can apply the UNIQUE constraint to multiple columns, ensuring the combination of values is unique.


Example
CREATE TABLE enrollments (
student_id INT,
course_id INT,
CONSTRAINT unique_enrollment UNIQUE (student_id, course_id)
);

Explanation:

  • No student can enroll in the same course more than once.