Skip to content
Advertisement

Creating a table with 2 primary keys and two foreign keys referring to 2 different tables with same constraint name

For this particular schema:

This is the schema

I have created the department student and subject tables now the problem right now arises in the creation of the mark table.

It is specified that there are 2 primary keys and 2 foreign keys , but as the title suggests creating 2 foreign keys referring to 2 different tables having the same constraint name seems impossible as per my understanding by surfing on the internet and reading on few threads here.

Is there any way to do this ? I want to have both the foreign key’s constraint name to be “fk”.

This code pops with a identifier error:

create table mark(
    value number,
    subject_id number,
    student_id number,
    constraint pk primary key(subject_id,student_id),
    constraint fk foreign key(subject_id,student_id) references subject(subject_id,student_id));

But even if i create 2 constraints with different name test cases fail. Is there a solution?

This is department table

create table department(
    department_id number(2),
    department_name varchar(30),
    department_block_number number,
    constraint PK primary key(department_id));

This is student table

create table student(
        student_id number,
        student_name varchar(30),
        address varchar(40),
        city varchar(30),
        department_id number,
        constraint pk primary key(student_id),
        constraint fk foreign key(department_id) references department(department_id));

This is staff table

create table staff(
    staff_id number,
    staff_name varchar(30),
    department_id number,
    constraint pk primary key(staff_id),
    constraint fk foreign key(department_id) references department(department_id));

Advertisement

Answer

You have a composite primary key – on more than one column – which is fine; but you can’t have a composite foreign key as the student table doesn’t have a subject_id column – hence it giving you an invalid-identifier error.

You need two foreign keys, something like:

create table mark(
    value number,
    subject_id number,
    student_id number,
    constraint mark_pk primary key(subject_id,student_id),
    constraint mark_fk_subject foreign key(subject_id) references subject(subject_id),
    constraint mark_fk_student foreign key(student_id) references student(student_id));

The constraint names have to be unique, both within and across tables in the same schema, and something more descriptive than ‘pk’ or ‘fk’ would be sensible anyway.

db<>fiddle

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement