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;| started | second | third | chained_third |
|---|---|---|---|
| 2026-01-31 | 2026-03-03 | 2026-03-31 | 2026-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;| started | clamped_second | third_month_end |
|---|---|---|
| 2026-01-31 | 2026-02-28 | 2026-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