Skip to Main Content
  • Questions
  • Add some extra constraint foreign-key in a table

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Ricardo.

Asked: February 14, 2025 - 10:42 am UTC

Last updated: February 14, 2025 - 5:46 pm UTC

Version: 19c

Viewed 100+ times

You Asked

Hi Tom,

I have a question regarding to add some constraint into a table.
I have 2 tables defined as:

create table TableA (
   fieldA varchar2(10),
   fieldB varchar2(10),
   fieldC varchar2(5),
   fieldD varchar2(10) not null,
   fieldE number(38) not null,
 Constraint TableAPK primary key (fieldE));


create table TableB(
   categorie varchar2(255),
   soort varchar(255) not null,
   code varchar(255) not null,
   status varchar(255),
  Constraint TableB primary key (code));


In TableA; the values from fieldA, fieldB, fieldC and fieldD are used to populate the TableB on column code.

The column soort in TableB is filled depending which kind of field are comming from TableA.

As example:

TableA
fieldA fieldB fieldC fieldD fieldE
—————- —————- —————- —————- —————-
PAS304 344555 PG1AA  36415  305

TableB
categorie soort code   status
————————- ————- —————- ——————
[null]    ALT   PAS304 free
[null]    MMS   344555 free
[null]    ROE   PG1AA  free
[null]    TOR   36415  free


My question:

It is possible to create new constraints foreign-keys in TableA for fieldA, fieldB, fieldC and fieldD with the fields from TableB (soort, code).

I tried something like this but I am not sure if this is what I want.

   ALTER TABLE TableA
ADD CONSTRAINT fieldA_FK
   FOREIGN KEY (fieldA)
REFERENCES TableB (CODE);

ALTER TABLE TableA
ADD CONSTRAINT fieldB_FK
   FOREIGN KEY (fieldB)
REFERENCES TableB (CODE);

etc




Thanks in advance for your answer.

With kind regards,
Ricardo Barrera Ramírez

and Chris said...

So you mean conditionally choose which column of A is the parent of a column in B?

If so, you can't do that.

It's unclear to me why you're trying to do this. Please share background into the problem you're trying to solve here and we'll see how we can help.