0

I'm newbie in oracle and trying to create a table with a foreign key, however, an error keeps appearing, and I don't know what is wrong.

This is the little code, and when I try to create "UNIDADESMEDIDA" the error pops up:

create table TIPOUNIDAD(
    ID_TIPOUNIDAD char(20) not null,
    constraint TIPOUNIDAD_PK primary key(ID_TIPOUNIDAD)
);

create table UNIDADESMEDIDA(
    ID_UNIDADMEDIDA integer not null,
    constraint UNIDADESMEDIDA_PK primary key(ID_UNIDADMEDIDA),
    constraint TIPOUNIDAD_FK foreign key(ID_TIPOUNIDAD) references TIPOUNIDAD(ID_TIPOUNIDAD)
);

Error report -
ORA-00904: "ID_TIPOUNIDAD": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:

Any suggestion?

1
  • What do you mean? the second table just have the column "ID_UNIDADMEDIDA", and I'm try to include the "ID_TIPOUNIDAD" as a foreign key Commented Jun 10, 2019 at 20:16

1 Answer 1

3

Declaring a foreign key constraint does not automatically create the column; you still need to declare that separately:

create table UNIDADESMEDIDA(
    ID_UNIDADMEDIDA integer not null,
    ID_TIPOUNIDAD char(20),
    constraint UNIDADESMEDIDA_PK primary key(ID_UNIDADMEDIDA),
    constraint TIPOUNIDAD_FK foreign key(ID_TIPOUNIDAD) references TIPOUNIDAD(ID_TIPOUNIDAD)
);

The column name doesn't have to be the same in both tables, and the child column can be nullable even if the parent is not. The data type needs to match though.

Incidentally, there is very rarely a reason to use the char datatype, you should probably change both the parent and child column to varchar2(20).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.