← Back to SQL, page 16

sql-0317 · Hard senior

Design a schema for hotel room bookings that prevents double booking.

Store bookings with room_id, check_in and check_out as a half-open date range. Prevent overlaps in PostgreSQL with an exclusion constraint on (room_id, daterange) using &&, which handles concurrency inside the database. Without that feature, lock the room row (or use one row per room-night with a unique key) inside the booking transaction.

Full answer

Tables: rooms(id, hotel_id, type), bookings(id, room_id, guest_id, check_in, check_out, status).

Two reliable ways to stop double booking:

  1. PostgreSQL exclusion constraint (needs btree_gist):
text
ALTER TABLE bookings ADD CONSTRAINT no_overlap
  EXCLUDE USING gist (room_id WITH =, daterange(check_in, check_out) WITH &&)
  WHERE (status <> 'cancelled');
  1. One row per room per night: room_nights(room_id, night, booking_id, PRIMARY KEY (room_id, night)). Inserting all nights in one transaction fails on any clash. This works on any engine, including SQLite.

Application checks ("is anything overlapping?" then insert) race under concurrency unless the room row is locked first with SELECT ... FOR UPDATE.

Half-open ranges let a guest check out on the same day another checks in. Availability searches then query for rooms with no overlapping booking, using the overlap test check_in < :end AND :start < check_out.

Key points

  • Model stays as half-open date ranges
  • PostgreSQL exclusion constraints prevent overlaps
  • One row per room-night with a unique key works anywhere
  • Check-then-insert races without locking

Common mistakes

  • Validating availability only in application code
  • Using closed ranges that block same-day turnover

Follow-ups

  • How would you search available rooms for given dates?
  • How would you hold a room for 10 minutes during checkout?

Tips

  • Name the concurrency hazard