05|Oracle learning (CHECK constraints)

1. Introduction to CHECK constraints

  • It is a check constraint, which is used to limit the values ​​that can be entered in each column to ensure the correctness of the data.
    • For example: the gender in the table below, we limit it to: male and female. Then the following gender has only these two values. Limitation is dead.
      insert image description here

2. Add CHECK constraints

2.1 Add constraints when creating a table

insert image description here

2.1.1 Case
  • Create a student information table and constrain the gender in it with Check
create table tb_students(
    stu_num char(5) not null,
    stu_name varchar(10) not null,
    stu_sex char(2) not null,
    primary key(stu_num),
    constraint ck_student_sex CHECK(stu_sex='男' or stu_sex='女')
);
  • If you want to limit the gender to "male" or "female" and limit the age of the students to [6,30] when creating the student information table, what should you do? as follows:
create table tb_students(
    stu_num char(5) not null,
    stu_name varchar(10) not null,
    stu_sex char(2) not null,
    stu_age number(2) not null,
    primary key(stu_num),
    constraint ck_student_sex CHECK(stu_sex='男' or stu_sex='女'),
    constraint ck_student_age check(stu_age between 6 and 30)
);

2.2 After creating the table, add constraints

insert image description here

2.2.1 Case
  • Create a student information table without CHECK constraints:
create table tb_students(
    stu_num char(5) not null,
    stu_name varchar(10) not null,
    stu_sex char(2) not null,
    stu_age number(2) not null,
    primary key(stu_num)
);

  • Next, add a CHECK constraint to the table, limiting gender to "male" or "female":
alter table tb_students 
add constraint ck_student_sex Check(stu_sex='男' or stu_sex='女');

3. Delete the CHECK constraint

  • Delete the ck_student_sex constraint in the student information table:
alter table tb_students
drop constraint ck_student_sex;

Guess you like

Origin blog.csdn.net/qq_41714549/article/details/132061147