Possible Duplicate:
Is using multiple foreign keys seperated by commas wrong, and if so, why?

I'm building online examination system. I have designed to table, Question and GeneralExam. The table GeneralExam contains info about the exam like name, description, duration,... Now I would like to design table GeneralQuestion, it will contains the id of questions belongs to a general exam.

Currently, I have two idea to design GeneralQuestion table:

  1. It will have two column: general_exam_id, question_id.
  2. It will have two column: general_exam_id, list_question_ids(string/text).

So, I would like to know which designing is better, or Pros and Cons of each designing. I'm using Postgresql database.

  • 4
    I wouldn't even really care about the performance - but if you use just a plain old list of strings - how do you ensure data integrity?? How can you make sure only valid ID's will be stored?? That's what foreign keys are for - ensuring data integrity (not performance....)
    – marc_s
    Nov 16 '12 at 11:23
  • 1
  • 2
  • 4
    I have to repeat this as well: do not store comma separated values in a single column. Just don't. Nov 16 '12 at 11:38
  • 4
    Don't worry about 100, 1000 or even 10'000 rows - any decent RDBMS will just laugh at such a number of rows..... being able to enforce data integrity is MUCH more important than having a few lookup tables with a few hundred or a few thousand rows more..... having dealt with loads of crappily designed databases without data integrity, I cannot stress enough just how important data integrity (and thus referential integrity on a database level) is .....
    – marc_s
    Nov 16 '12 at 12:55

As ypercube and marc_s pointed out, it's best to have a 2-column "mapping" table to store which questions are used by which general exams.

This approach provides the following benefits:

  • Foreign Keys can then be used to ensure data integrity
  • Queries are much easier to write (eg: find all general exams that use question 17)
  • Extending the database schema at a later date (to support new features) will be much easier
  • The schema will be easier to understand by new/other developers/DBAs since it confirms to best practice

Not the answer you're looking for? Browse other questions tagged or ask your own question.