MySQL : UNIQUE Constraint

In MySQL, the UNIQUE constraint is used to ensure that all values in a column or a group of columns are unique, meaning no two rows can have the same value(s) in the specified column(s).

Here's how you can use the UNIQUE constraint while creating a table:


CREATE TABLE table_name (
    column_name data_type UNIQUE,
    ...
);

 

You can also apply the UNIQUE constraint to multiple columns:


CREATE TABLE table_name (
    column1_name data_type,
    column2_name data_type,
    ...
    UNIQUE(column1_name, column2_name)
);

For example, suppose you have a table named students and you want to ensure that the email column contains unique values:


CREATE TABLE students (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100) UNIQUE
);

 

In this example, the email column is defined with the UNIQUE constraint, which means that each email address must be unique in the students table. Attempting to insert a row with an email address that already exists in the table will result in an error.

Using the UNIQUE constraint is useful for enforcing data integrity and preventing duplicate entries in a column or group of columns. It ensures that the data in your database remains consistent and accurate.