สร้างตารางพร้อม Unique Constraint
mysql> create table UniqueConstraintDemo (
-> Name varchar(200) unique
-> );
Query OK, 0 rows affected (1.05 sec)
ตรวจสอบโครงสร้าง
mysql> DESC UniqueConstraintDemo;
+-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | Name | varchar(200) | YES | UNI | NULL | | +-------+--------------+------+-----+---------+-------+ 1 row in set (0.00 sec)
คอลัมน์ Key แสดง UNI หมายถึง Unique
ทดสอบข้อจำกัด
mysql> insert into UniqueConstraintDemo values('John');
Query OK, 1 row affected (0.54 sec)
mysql> insert into UniqueConstraintDemo values('John');
ERROR 1062 (23000): Duplicate entry 'John' for key 'Name'
คำสั่งลบ Unique Constraint
DROP INDEX yourColumnName ON yourTableName;
นำไปใช้งาน
mysql> DROP INDEX Name ON UniqueConstraintDemo; Query OK, 0 rows affected (0.39 sec) Records: 0 Duplicates: 0 Warnings: 0
ตรวจสอบอีกครั้ง
mysql> DESC UniqueConstraintDemo;
+-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | Name | varchar(200) | YES | | NULL | | +-------+--------------+------+-----+---------+-------+ 1 row in set (0.00 sec)
คอลัมน์ Key ว่างเปล่า แสดงว่า Unique Constraint ถูกลบเรียบร้อยแล้ว