1. Introduction to UNIQUE constraints
- Also called: unique key constraint, used to limit the uniqueness of field values in the data table.
1.1 Difference between UNIQUE and primary key:
- There is only one primary key/combined primary key per table.
- UNIQUE constraints can exist in multiple fields in a table. For example: the student's phone number and ID number are unique.
2. Add a unique constraint
2.1 Add when creating a table
2.1.1 Case
- Create a student information table and set the phone number as the only constraint:
create table tb_students(
stu_num char(5) not null,
stu_name varchar(10) not null,
stu_sex char(1) not null,
stu_age number(2) not null,
stu_tel char(11) not null,
constraint uq_student_tel UNIQUE(stu_tel)
);
In actual development, the following are commonly used, just add a unique directly after stu_tel:
create table tb_students(
stu_num char(5) not null,
stu_name varchar(10) not null,
stu_sex char(1) not null,
stu_age number(2) not null,
stu_tel char(11) not null unique
);
2.2 After creating the table, add it
2.2.1 Case
- Create a student information table without a unique key:
create table tb_students(
stu_num char(5) not null,
stu_name varchar(10) not null,
stu_sex char(1) not null,
stu_age number(2) not null,
stu_tel char(11) not null
);
- Then add a unique key to the table: stu_tel:
alter table tb_students
add constraint uq_student_tel
unique(stu_tel);
3. Remove the unique constraint
3.1 Case
- Drop the unique constraint uq_student_tel:
alter table tb_students
drop constraint uq_student_tel;