I am trying to model a quiz structure, where there are questions and a unlimited number of answers, where only one is correct.
Example:
Question A
- Answer A
- Answer B
- Answer C (Correct Answer)
- Answer D
Question B
- Answer A
- Answer B (Correct Answer)
Given the requirements I came with the following structure:
CREATE TABLE question (
id int PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
correct_answer_id int NOT NULL
);
CREATE TABLE answer (
id int PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
question_id int NOT NULL
);
ALTER TABLE question ADD CONSTRAINT q_a_fk
FOREIGN KEY (correct_answer_id) REFERENCES answer(id);
ALTER TABLE answer ADD CONSTRAINT a_q_fk
FOREIGN KEY (question_id) REFERENCES question(id);
However I am having problems inserting data. Is it possible to insert this structure via a CTE or deferrable FK within a transaction?
Edit: I would like to guarantee that no question is inserted without a correct answer.