Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When creating foreign key constraint, is column name needed?

Let's say we have two tables created by following script:

create table CAR (
    CAR_ID number(19,0),
    NAME varchar2(255 char),
    primary key (CAR_ID)
);
create table CAR_WHEEL (
    CAR_WHEEL_ID number(19,0),
    CAR_REF_ID number(19,0),
    WHEEL_COLOR varchar2(255 char),
    primary key (CAR_WHEEL_ID)
);

Now I want to add a constraint, so I can create this statement:

alter table CAR_WHEEL
    add constraint FK_CAR 
    foreign key (CAR_REF_ID) 
    references CAR (CAR_ID);

But I saw also scripts, where there would be references CAR; in last line, instead of references CAR (CAR_ID);

What is the difference and when should I add column names? Would there be any change if CAR table had primary key with more columns, e.g. primary key (CAR_ID, NAME)?

If the answer depends on SQL dialect, I am particulary interested in Oracle.

like image 375
zuroslav Avatar asked Sep 14 '25 00:09

zuroslav


1 Answers

Foreign key without specific column will create it on the primary key, so with different primary key you need to add all the columns from it. I would not recomend using the implicit foreign key creation.

like image 146
dimo raichev Avatar answered Sep 16 '25 16:09

dimo raichev