← Back to SQL, page 19

sql-0369 · Hard senior

How would you store recurring calendar events, such as a meeting every Tuesday?

Store the series once with a recurrence rule (for example an RRULE string), the start time in the organiser's time zone and an optional end, plus an exceptions table for moved or cancelled occurrences. Expand occurrences for the requested date range in the application or a function, and optionally materialise the next few months for fast queries.

Full answer
text
event_series(id, title, starts_local TIMESTAMP, tz TEXT, duration INTERVAL,
             rrule TEXT, until DATE)                   -- 'FREQ=WEEKLY;BYDAY=TU'
event_exceptions(series_id, original_start, new_start, cancelled BOOLEAN,
                 PRIMARY KEY (series_id, original_start))

Why store local time plus zone: a 10:00 meeting in London stays at 10:00 local across daylight saving changes; storing a fixed UTC time would shift it by an hour twice a year.

Querying a week view:

  1. Expand rules into occurrences between the view's start and end.
  2. Apply exceptions (skip cancelled, move rescheduled).
  3. Convert to the viewer's time zone.

Materialising occurrences into an event_instances table for a rolling window makes availability queries simple SQL, at the cost of regenerating them when the rule changes. Editing "this and following" events splits the series into two.

Key points

  • Store the rule, not every occurrence
  • Keep local time and time zone
  • Exceptions table for changes
  • Expand per date range
  • Optionally materialise a rolling window

Common mistakes

  • Storing recurring events in UTC only
  • Generating occurrences forever

Follow-ups

  • How would you find free slots for several people?
  • How would you edit all future occurrences?

Tips

  • Explain the time zone choice