Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Foreign key does not exist error? Oracle SQL

I’m creating a database and making some tables.

I have a table ‘written_by’ which references table ‘author’ and ‘book’
the creating code is as below.

CREATE TABLE WRITTEN_BY (
  NAME VARCHAR2(20),
  ADDRESS VARCHAR2(30),
  ISBN VARCHAR2(30),
  CONSTRAINT WB_FK FOREIGN KEY(NAME)
  REFERENCES AUTHOR(NAME),
  CONSTRAINT WB_FK2 FOREIGN KEY(ADDRESS)
  REFERENCES AUTHOR(ADDRESS),
  CONSTRAINT WB_FK3 FOREIGN KEY(ISBN)
  REFERENCES BOOK(ISBN)
);

When the code is executed, the script returns ‘no primary key existing’, but as searched by

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner
FROM all_constraints cons, all_cons_columns cols
WHERE cons.constraint_type = 'P'
AND cons.constraint_name = cols.constraint_name
AND cons.owner = cols.owner
ORDER BY cols.table_name, cols.position;

There are primary key ‘name’, ‘address’, and ‘ISBN’.

*edit
Here’s the ‘author’ table creating code.

CREATE TABLE AUTHOR (
  NAME VARCHAR2(20),
  ADDRESS VARCHAR2(30),
  URL VARCHAR2(100),
  CONSTRAINT A_PK PRIMARY KEY(NAME, ADDRESS)
);

>Solution :

You want to use the composite key:

CREATE TABLE WRITTEN_BY (
  NAME VARCHAR2(20),
  ADDRESS VARCHAR2(30),
  ISBN VARCHAR2(30),
  CONSTRAINT WB_FK FOREIGN KEY(NAME, ADDRESS)
  REFERENCES AUTHOR(NAME, ADDRESS),
  CONSTRAINT WB_FK3 FOREIGN KEY(ISBN)
  REFERENCES BOOK(ISBN)
);

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading