← Back to SQL, page 20

sql-0393 · Hard senior

Design a clinic appointment system where patients book 15-minute slots with doctors.

Store doctors' working hours as rules, generate bookable slots (or compute them), and store appointments with doctor_id and start time under a unique constraint so a slot can be booked only once. In PostgreSQL an exclusion constraint on (doctor_id, tsrange) also prevents overlapping appointments of different lengths.

Full answer
text
doctors(id, name, tz)
working_hours(doctor_id, weekday, start_local, end_local)
time_off(doctor_id, starts_at, ends_at)
appointments(id, doctor_id, patient_id, starts_at timestamptz, ends_at timestamptz,
             status, UNIQUE (doctor_id, starts_at))

Availability for a day: generate 15-minute starts within working hours, remove time off and existing non-cancelled appointments. Generating slots on the fly avoids storing millions of empty rows; a materialised slots table for the next few weeks is the alternative when searches are heavy.

Double booking:

  • Fixed slot lengths: the unique key on (doctor_id, starts_at) is enough; two concurrent inserts for the same slot cannot both succeed.
  • Variable lengths: EXCLUDE USING gist (doctor_id WITH =, tstzrange(starts_at, ends_at) WITH &&) WHERE (status <> 'cancelled').

Store instants in UTC and working hours in the doctor's local time, so daylight saving changes keep clinic hours correct. Cancelled appointments should free the slot, which the partial constraint handles.

Key points

  • Rules for working hours, rows for bookings
  • Unique (doctor_id, starts_at) for fixed slots
  • Exclusion constraints for variable lengths
  • Compute or materialise availability
  • Local working hours, UTC instants

Common mistakes

  • Checking availability in code without a constraint
  • A unique constraint that also blocks rebooking after cancellation

Follow-ups

  • How would you support group sessions with several patients?
  • How would reminders be scheduled?

Tips

  • Show the constraint that prevents double booking