Ice
Ice

Reputation: 1971

How to add unique constraint as foreign key ?

I am trying to add unique constraint as foreign key by this statement:

ALTER TABLE SOME_TABLE ADD(
CONSTRAINT FK_ID FOREIGN KEY (S_ID) REFERENCES OTHER_TABLE(O_ID) UNIQUE (S_ID)
);

I thought that this statement is correct, but all time I got "missing right parenthesis error". Probably I have wrong order of key words. Could you give me advice how to create an unique constraint ?

I red this issue:

Add a unique constraint of a sql table as foreign key reference to an another sql table

but still I have problem with this.

Upvotes: 0

Views: 8472

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269873

First, you don't need parentheses. Second, this is two constraints and you might as well give both names:

ALTER TABLE SOME_TABLE
    ADD CONSTRAINT FK_ID FOREIGN KEY (S_ID) REFERENCES OTHER_TABLE(O_ID);

ALTER TABLE SOME_TABLE
    ADD CONSTRAINT UNQ_ST_S_ID UNIQUE (S_ID);

Upvotes: 3

Related Questions