← Back to SQL, page 18

sql-0349 · Hard senior

Design the tables for selling reserved seats at events without selling a seat twice.

Create a row per seat per event (event_seats) with a status and an optional hold expiry, and a unique constraint so each seat belongs to at most one ticket. Holding a seat is a conditional UPDATE from available to held; purchase changes held to sold in the same transaction as payment recording. Expired holds are released by a job or treated as available by queries.

Full answer
text
events(id, venue_id, starts_at)
seats(id, venue_id, section, row_label, number)
event_seats(event_id, seat_id, status CHECK IN ('available','held','sold'),
            held_by, hold_expires_at, PRIMARY KEY (event_id, seat_id))
tickets(id, event_id, seat_id, order_id, UNIQUE (event_id, seat_id))

Holding seats:

text
UPDATE event_seats SET status = 'held', held_by = :cart, hold_expires_at = now() + interval '10 minutes'
WHERE event_id = :e AND seat_id = ANY(:seats)
  AND (status = 'available' OR (status = 'held' AND hold_expires_at < now()));

If the affected row count is less than the number requested, some seats were taken; roll back and tell the user. The atomic conditional update avoids a race between checking and holding.

The UNIQUE on tickets is the final guarantee against double sale. For very popular events, a queue in front of the hold step limits contention on the same rows.

Key points

  • One row per seat per event
  • Conditional UPDATE to hold seats atomically
  • Holds expire
  • A unique ticket constraint is the final guarantee
  • Compare affected rows with seats requested

Common mistakes

  • Checking availability and then updating in two steps without locks
  • Holds that never expire

Follow-ups

  • How would you support general admission tickets?
  • How would you handle payment failures after a hold?

Tips

  • Show the atomic hold