How can we apply UNIQUE constraint to the field of an existing MySQL table?

MySQLMySQLi Database

We can apply the UNIQUE constraint to a column of an existing MySQL table with the help of ALTER TABLE statement.

Syntax

ALTER TABLE table_name MODIFY colum_name datatype UNIQUE;
                    OR
ALTER TABLE table_name ADD UNIQUE (colum_name);

Example

Suppose we have the following table named ‘Test4’ and we want to add UNIQUE constraint to the column ‘Name’ then it can be done with the help of ALTER TABLE command as follows −

mysql> DESCRIBE test4;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID    | int(11)     | YES  | UNI | NULL    |       |
| Name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.04 sec)

mysql> ALTER TABLE test4 MODIFY Name Varchar(20) UNIQUE;
Query OK, 0 rows affected (0.22 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> DESCRIBE test4;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID    | int(11)     | YES  | UNI | NULL    |       |
| Name  | varchar(20) | YES  | UNI | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.04 sec)

From the above result set, it can be observed that MySQL added a UNIQUE constraint to the filed ‘Name’. We can add a UNIQUE constraint with the following query as well −

mysql> Alter table test4 add UNIQUE(name);
Query OK, 0 rows affected (0.16 sec)
Records: 0 Duplicates: 0 Warnings: 0
raja
Published on 16-Feb-2018 17:04:05
Advertisements