samjam
samjam

Reputation: 209

oracle sql: not able to add foreign key to table -> invalid identifier?

First off, I'm a real newbie to db and sql. However, I have to tables, PERSON and SPECIES and I want to add a foreign key to the table SPECIES. When trying to add the foreign key I always get the error message "ORA-900904: invalid identifier". I just can't figure out what I've done wrong and why it doesn't work?!?!

This was my approach:

PERSON table and primary key

create table person
(
name varchar2 (30),
firstname varchar2 (30),
persid number (8) not null
)
;

alter table person 
add constraint person_pk 
primary key (persid)
;

SPECIES table and primary key

create table species
(
speciesnamelat varchar2 (30),
vartid number (8) not null
)
;

alter table Species
add constraint species_pk
primary key (vartid)
;

This part worked fine but the following didn't work:

Foreign Key for SPECIES referring to PERSON

alter table species
add constraint species_person_fk
foreign key (persid)
references person (persid)
;

I always get this Error "ORA-900904: invalid identifier"

Upvotes: 4

Views: 15104

Answers (1)

Yahia
Yahia

Reputation: 70369

you are refereing to persid which is not a column in table species thus the error...

EDIT - As per comments:

It means that you need some column in species to be used as foreign key... if there is no such column then you need to build one in before you can create that constraint. Like this:

alter table species
add persid number(8) not null
;
alter table species
add constraint species_person_fk
foreign key (persid)
references person (persid)
;

Depending on your data model, SPECIES.PERSID may be optional or mandatory.

Upvotes: 5

Related Questions