← Back to SQL, page 25

sql-0495 · Hard senior

A subscription renews on the 31st of each month, but adding one month with date arithmetic gives dates like 3 March. How should month-end renewals work?

Adding one month to 31 January is ambiguous because February has no 31st. SQLite's date function overflows into the next month (31 January plus one month becomes 3 March), while PostgreSQL clamps to the last day of the month. Store the intended day of month and compute each renewal from the original anchor date, clamped to month end, instead of adding a month to the previous renewal.

Full answer
sql
CREATE TABLE subs (id INTEGER PRIMARY KEY, started TEXT);
INSERT INTO subs VALUES (1, '2026-01-31');

The query as written:

sql
SELECT started, date(started, '+1 month') AS second, date(started, '+2 month') AS third, date(date(started, '+1 month'), '+1 month') AS chained_third FROM subs;
startedsecondthirdchained_third
2026-01-312026-03-032026-03-312026-04-03

Overflow moves the second renewal to 3 March, and chaining month additions from that overflowed date drifts the schedule further from the 31st.

A corrected version:

sql
SELECT started, MIN(date(started, '+1 month'), date(started, 'start of month', '+2 month', '-1 day')) AS clamped_second, date(started, 'start of month', '+3 month', '-1 day') AS third_month_end FROM subs;
startedclamped_secondthird_month_end
2026-01-312026-02-282026-03-31

Clamping takes the smaller of the overflowed date and the last day of the target month, which gives 28 February; the March renewal is month end again because the anchor day (31) is kept in the schedule, not copied from the previous renewal. In PostgreSQL, started + interval '1 month' already clamps, but chaining intervals still drifts (31 Jan, 28 Feb, 28 Mar), so renewals should always be computed from the anchor. The PostgreSQL behaviour here is stated, not run.

sql
CREATE TABLE subs (id INTEGER PRIMARY KEY, started TEXT);
INSERT INTO subs VALUES (1, '2026-01-31');

SELECT started, date(started, '+1 month') AS second, date(started, '+2 month') AS third, date(date(started, '+1 month'), '+1 month') AS chained_third FROM subs;

SELECT started, MIN(date(started, '+1 month'), date(started, 'start of month', '+2 month', '-1 day')) AS clamped_second, date(started, 'start of month', '+3 month', '-1 day') AS third_month_end FROM subs;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Month arithmetic is ambiguous at month end
  • SQLite overflows, PostgreSQL clamps
  • Compute each cycle from the anchor date
  • Clamp to the last day of the target month

Common mistakes

  • Adding a month to the previous renewal date
  • Assuming all databases handle month ends the same way

Follow-ups

  • How would you handle leap years for annual renewals?
  • How would you test renewal dates for every start day?

Tips

  • Use 31 January as the example