0

I'm having difficulties adding a constraint with two constraint conditions to an already existing table. I'm working with the two relations below, and I'm trying to add the constraint to the "books" table.

The relations are:

  1. books((book_id), title, author_id, subject_id)

  2. subjects((subject_id), subject, location)

Where the keys within the parantheses are primary keys, and the italics are foreign keys.

The first criteria/condition is that the subject_id is NOT NULL, and that the subject_id when inserting a new book-tuple into books, already has to exist as a primary key in the subjects relation.

ALTER TABLE books ADD CONSTRAINT hasSubject 
    CHECK(subject_id IS NOT NULL AND subject_id REFERENCES subjects(subject_id))

I keep getting the error message: "syntax error at or near 'REFERENCES'"

Any ideas? Thank you in advance!

1 Answer 1

2

REFERENCES is a separate type of constraint. So, you need two constraints:

ALTER TABLE books ADD CONSTRAINT chk_books_subject_id
    CHECK (subject_id IS NOT NULL);

ALTER TABLE books ADD CONSTRAINT fk_books_subject_id
    FOREIGN KEY (subject_id) REFERENCES subjects(subject_id);

I put these in two ALTER TABLE statements, to emphasize that they are different. They can be combined in one statement.

EDIT:

In one statement:

ALTER TABLE books
    ADD CONSTRAINT chk_books_subject_id CHECK (subject_id IS NOT NULL),
    ADD CONSTRAINT fk_books_subject_id FOREIGN KEY (subject_id) REFERENCES subjects(subject_id);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! Would you care to show how to combine these two constraints? I tried combining the two with an "AND" statement. So: "... IS NOT NULL) AND FOREIGN KEY(subject_id) ...", but recieved a syntax error message complaining "at or near "AND".
Once again, thank you!! :) Would it be possible to join the two constraints and refer to them with one mutual name "hasSubjects"? In other words, is it possible to rewrite this single statement with only one "ADD CONSTRAINT" term, whilst keeping the same functionality?
@Ninu . . . No, that is not possible. There are two constraints.

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.