03|Oracle learning (primary key constraints, joint primary keys)

1. Introduction to primary key constraints

  • Primary key: One or more fields in the data table, used to uniquely identify a record in the data table.

2. Add primary key constraints

2.1 Add constraints when creating a table

insert image description here
Writing 1:

CREATE TABLE tb_students(
    stu_num char(5) primary key,
    stu_name varchar(10) not null,
    stu_sex char(1) not null,
    stu_age number(2) not null,
    stu_tel char(11) not null
);

Writing method 2 (written in the back):

CREATE TABLE tb_students(
    stu_num char(5),
    stu_name varchar(10) not null,
    stu_sex char(1) not null,
    stu_age number(2) not null,
    stu_tel char(11) not null,
    primary key(stu_num)
);

2.2 Add constraints after creating the table

Change the following to: ADD CONSTRAINTS
insert image description here
For example: You have now created a student information table td_students without constraints

CREATE TABLE tb_students(
    stu_num char(5),
    stu_name varchar(10) not null,
    stu_sex char(1) not null,
    stu_age number(2) not null,
    stu_tel char(11) not null
);

Now we can add the primary key to stu_nums in the td_students table with the following code:

ALTER TABLE tb_students ADD CONSTRAINTS pk_students PRIMARY KEY(stu_num);

insert image description here

3. Combined primary key

  • Combined primary key: use 2 or more fields as the primary key

4. Add a composite primary key

4.1 Add a combined primary key when creating a table

insert image description here
Create a grade table tb_grades

CREATE TABLE tb_grades(
    course_id char(3),
    course_name varchar2(50),
    stu_num char(5),
    stu_name varchar2(10),
    score number(3),
    primary key(course_id,stu_num)
);

4.2 Create the table first, then add the joint primary key

Change the following to: ADD CONSTRAINTS
insert image description here
First create a score table without constraints:

CREATE TABLE tb_grades(
    course_id char(3),
    course_name varchar2(50),
    stu_num char(5),
    stu_name varchar2(10),
    score number(3)
);

add constraints

ALTER TABLE tb_grades ADD CONSTRAINTS pk_grades PRIMARY KEY(course_id,stu_num);

Guess you like

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