← Back to SQL, page 21

sql-0404 · Medium mid

Design a school timetable database that prevents a teacher or room from being double-booked in the same period.

Model teachers, rooms, class groups, subjects and periods (day plus slot number), and a lessons table assigning a group, subject, teacher and room to a period. Unique constraints on (period_id, teacher_id), (period_id, room_id) and (period_id, group_id) make each double booking impossible in the database itself.

Full answer
text
periods(id, weekday, slot, starts_at, ends_at, UNIQUE (weekday, slot))
teachers(id, name)   rooms(id, name, capacity)   class_groups(id, name, size)
subjects(id, name)
lessons(id, term_id, period_id FK, group_id FK, subject_id FK, teacher_id FK, room_id FK,
        UNIQUE (term_id, period_id, teacher_id),
        UNIQUE (term_id, period_id, room_id),
        UNIQUE (term_id, period_id, group_id))

Three unique keys capture three separate rules: a teacher teaches one lesson per period, a room hosts one lesson, a group attends one lesson. Including term_id lets each term have its own timetable.

Other rules, such as room capacity at least group size or a teacher's maximum periods per day, need a trigger or validation in the scheduling application. Generating a good timetable is an optimisation problem solved outside SQL; the database's job is to reject invalid results.

Key points

  • Periods as day plus slot
  • One unique key per double-booking rule
  • Term scoping
  • Triggers or app checks for capacity rules
  • Generation happens outside SQL

Common mistakes

  • Checking clashes only in the UI
  • Storing timetables as free text per teacher

Follow-ups

  • How would you handle double periods?
  • How would substitute teachers be recorded?

Tips

  • Map each rule to a constraint