← Back to SQL, page 21

sql-0405 · Hard senior

Design storage for ride trips: requests, driver assignment, status changes and fares.

Keep trips with rider, driver (nullable until assigned), status, pickup and drop-off points and timestamps, plus a trip_events table logging each status change. Assign a driver with a conditional UPDATE that only succeeds while the trip is still 'requested' and the driver is available, so two drivers cannot accept the same trip. Store the fare breakdown at completion.

Full answer
text
trips(id, rider_id, driver_id NULL, status CHECK IN ('requested','accepted','arrived',
      'in_progress','completed','cancelled'), pickup, dropoff, requested_at, completed_at)
trip_events(id, trip_id, from_status, to_status, actor, at)
driver_status(driver_id PK, state CHECK IN ('offline','available','on_trip'), updated_at)
fares(trip_id PK, base_minor, distance_minor, time_minor, surge_multiplier, total_minor)

Accepting a trip, in one transaction:

  1. UPDATE trips SET driver_id = :d, status = 'accepted' WHERE id = :t AND status = 'requested';
  2. UPDATE driver_status SET state = 'on_trip' WHERE driver_id = :d AND state = 'available';
  3. If either affects zero rows, roll back; another driver won or this driver is busy.

Allowed transitions form a state machine; enforce them in one place (a function or trigger) and log each to trip_events. Live locations are high-volume and usually live in a separate store, with only key points kept on the trip.

Key points

  • Trips as a state machine
  • Conditional updates for assignment
  • Event log of status changes
  • Fare breakdown stored at completion
  • Live location kept separately

Common mistakes

  • Letting any status change to any other
  • Assigning drivers with read-then-write logic

Follow-ups

  • How would you match the nearest available driver?
  • How would you handle a driver who cancels after accepting?

Tips

  • Show the two conditional updates