UNIQUE Constraint Syntax

The syntax for using UNIQUE constraints in MySQL can vary depending on whether you are adding constraints during creation or while updating the table. You can use the following syntaxes depending on the situation.

UNIQUE Constraint on CREATE TABLE

To add a UNIQUE Constraint on the CREATE TABLE statement, use the following syntax:

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

Syntax to add UNIQUE constraint on multiple columns:

CREATE TABLE table_name (
column_name1 data_type,
column_name2 data_type,
...
UNIQUE (column_name1, column_name2)
);

UNIQUE Constraint on ALTER TABLE

To add UNIQUE constraint while updating the table, use the following syntax:

ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column_name);

MySQL UNIQUE Constraint

MySQL UNIQUE constraint ensures that the values in a column or group of columns remain unique, preventing duplicate entries in a column and maintaining the integrity of the table.

Similar Reads

UNIQUE Constraint in MySQL

A UNIQUE constraint in MySQL prevents two records from having identical values in a column. A UNIQUE constraint can contain null values as long as the combination of values is unique. This makes it different from PRIMARY KEY as the primary key constraint can not contain null values....

UNIQUE Constraint Syntax

The syntax for using UNIQUE constraints in MySQL can vary depending on whether you are adding constraints during creation or while updating the table. You can use the following syntaxes depending on the situation....

MySQL UNIQUE Constraint Example

Suppose we have a table named products with a product_code column where we initially set a UNIQUE constraint to ensure each product code is unique:...

DROP the UNIQUE Constraint

To remove the UNIQUE constraint, we need to use a simple command:...

Adding a Unique Key with ALTER TABLE

Using the ALTER TABLE statement, you can add a UNIQUE constraint to an existing table....

Conclusion

The UNIQUE constraint in MySQL ensures of data integrity within databases, ensuring that specific columns or combinations of columns contain unique values. By preventing duplicates, it maintains accuracy and reliability in the stored information....