← Back to SQL, page 21

sql-0402 · Medium mid

Design storage for survey questions and responses where surveys can have different question types.

Store surveys, questions (survey, position, type, settings) and options for choice questions. Responses get a header row per submission and answer rows per question, with typed columns (option_id, text_value, number_value) or a JSON value. Keep questions versioned or immutable once responses exist, so old answers stay interpretable.

Full answer
text
surveys(id, title, published_at)
questions(id, survey_id, position, kind CHECK IN ('single','multi','text','scale'), prompt, required)
question_options(id, question_id, position, label)
responses(id, survey_id, respondent_id, submitted_at)
answers(response_id, question_id, option_id, text_value, number_value)
  • Multiple-choice answers are one row per selected option.
  • A CHECK can tie value columns to question types loosely; strict checks need a trigger.
  • Reports are plain aggregates: COUNT(*) GROUP BY option_id for a question.
  • Editing a published question's meaning invalidates earlier answers, so publish a new question instead and hide the old one.

A single JSON document per response is simpler to write but makes cross-response reporting slower and harder to validate; the row-per-answer shape keeps reporting in SQL.

Key points

  • Questions with type and position
  • Options table for choice questions
  • Answer rows per question with typed values
  • Freeze questions after responses exist
  • Row-per-answer keeps reporting simple

Common mistakes

  • Storing all answers as one comma-separated string
  • Editing published questions in place

Follow-ups

  • How would you support conditional questions?
  • How would you export responses as one row per respondent?

Tips

  • Explain why questions are frozen