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

Referencing a non-PK field in Oracle

What is the correct way to reference a non-PK field? I don’t understand why this example doesn’t work (the field c23).

CREATE TABLE tabla1 (
    c11 CHAR(9) PRIMARY KEY,
    c12 VARCHAR2(10),  
    c13 INTEGER,
    CHECK(c13 <= 100)
);

CREATE TABLE tabla2 (
    c21 CHAR(9) PRIMARY KEY,
    c22 VARCHAR2(10),  
    c23 REFERENCES tabla1(c13)
);

>Solution :

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

You can’t. If you want to create a foreign key constraint, you have to reference a primary or unique key column. Any other column won’t work.

For example:

SQL> CREATE TABLE tabla1 (
  2      c11 CHAR(9)      PRIMARY KEY,
  3      c12 VARCHAR2(10),
  4      c13 INTEGER      UNIQUE,
  5      CHECK(c13 <= 100)
  6  );

Table created.

SQL> CREATE TABLE tabla2 (
  2      c21 CHAR(9) PRIMARY KEY  REFERENCES tabla1 (c11),
  3      c22 VARCHAR2(10),
  4      c23 INTEGER              REFERENCES tabla1(c13)
  5  );

Table created.

SQL>
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