2

I have a table DEPENDENT

CREATE TABLE DEPENDANT (DEPENDANT_NM VARCHAR2(15) PRIMARY KEY,
  DEP_GENDER CHAR(1), DEP_BDAT DATE, RELATED_HOW VARCHAR2 (8), ESSNO CHAR(9));
ALTER TABLE DEPENDANT ADD CONSTRAINT FK_ESSNO FOREIGN KEY (ESSNO)
 REFERENCES HW_EMPLOYEE(SSNO);
ALTER TABLE DEPENDANT ADD CONSTRAINT CK_DEP_GENDER CHECK
(DEP_GENDER IN ('M','F'));

I need to add a constraint that makes sure that female dependents can only be realted as 'daughter' or 'spouse' and male dependents or only 'son' or 'spouse'

Do I use a check constraint like ...

ALTER TABLE DEPENDANT ADD CONSTRAINT CK_RELATEDF CHECK (DEP_GENDER = 'F' AND 
RELATED_HOW IN('Daughter' OR 'Spouse'));
0

2 Answers 2

2

You have to write it like this:

ALTER TABLE DEPENDANT 
    ADD CONSTRAINT CK_RELATEDF 
        CHECK (DEP_GENDER = 'F' AND RELATED_HOW IN ('Daughter', 'Spouse'));

Edit: you have to do it in one check:

ALTER TABLE DEPENDANT ADD CONSTRAINT CK_RELATEDF
  CHECK ((DEP_GENDER = 'F' AND RELATED_HOW IN ('Daughter', 'Spouse'))
    OR (DEP_GENDER = 'M' AND RELATED_HOW IN ('Son', 'Spouse')));
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, then I just make an almost identical constraint for males, correct?
@user1873736 You have to do it in one check, I've edited my answer.
"you have to do it in one check" -- why do you say this? See my answer.
2

"you have to do it in one check"

I was intrigued by this assertion (no pun intended).

It seems to me that four constraints are not only possible but desirable (to provide increased granularity of failure messages) e.g.

ALTER TABLE DEPENDANT ADD CONSTRAINT Gender_legal_values 
    CHECK ( DEP_GENDER IN ( 'M', 'F' ) );

ALTER TABLE DEPENDANT ADD CONSTRAINT Related_legal_values 
    CHECK ( RELATED_HOW IN ( 'Son', 'Daughter', 'Spouse' ) );

ALTER TABLE DEPENDANT ADD CONSTRAINT Female_legal_values
    CHECK ( DEP_GENDER = 'M' OR RELATED_HOW IN ( 'Daughter', 'Spouse' ) );

ALTER TABLE DEPENDANT ADD CONSTRAINT Male_legal_values
    CHECK ( DEP_GENDER = 'F' OR RELATED_HOW IN ( 'Son', 'Spouse' ) );

1 Comment

Read the author's comment - he asked if he is supposed to add additional trigger for dep_gender = 'M'. If he did that, he would end up with two checks that would not allow any record to be inserted into the table. That's why I said that he has to do it in one check, not two how he was going to. +1 for those checks.

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.