I am trying to create a database to store some questions and answers for a quiz
I have so far two tables:
questions: (Question ID(PK), question string, correct answer ID)
answers: (Answer ID(PK), answer string, question ID)
I’m having trouble setting up the foreign key constraints. Surely I need to make sure that correct answer ID exists in answers and that also question ID in answers exists in the questions table. However, when trying to add these foreign keys in SQliteStudio, I am getting errors which suggest I cannot add a foreign key referencing table A > B when there is already a foreign key constraint that goes from B > A.
This behavior is correct. Otherwise, you’d get a chicken-and-egg problem: you would not be able to insert an answer without inserting a row for the question first, and you also would not be able to insert a question without first inserting a valid answer for it. You will get a similar issue trying to delete a question or an answer being referenced.
A typical solution to this is adding a column
is_correctto theanswertable.