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.



Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.