← Back to SQL, page 21

sql-0412 · Medium mid

Predict the last day of the month for February 2028 and March 2026 using SQLite date modifiers.

date(d, 'start of month', '+1 month', '-1 day') returns the last day of d's month: 2028-02-29 for February 2028, a leap year, and 2026-03-31 for March 2026. Moving to the first of the month before adding a month avoids SQLite's overflow of invalid dates.

Full answer
sql
SELECT date('2028-02-10', 'start of month', '+1 month', '-1 day') AS feb_2028, date('2026-03-15', 'start of month', '+1 month', '-1 day') AS mar_2026;
feb_2028mar_2026
2028-02-292026-03-31

The modifiers apply left to right. 'start of month' moves to the 1st, '+1 month' moves to the 1st of the next month, which always exists, and '-1 day' steps back to the last day, so leap years are handled without any calendar logic. Adding a month directly to a 31st can overflow into the following month in SQLite, which is why the start-of-month step comes first. In PostgreSQL the same idea is (date_trunc('month', d) + interval '1 month - 1 day')::date (not run here).

sql
SELECT date('2028-02-10', 'start of month', '+1 month', '-1 day') AS feb_2028, date('2026-03-15', 'start of month', '+1 month', '-1 day') AS mar_2026;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Modifiers apply left to right
  • start of month, +1 month, -1 day gives month end
  • Leap years are handled automatically
  • Avoid adding months to day 31 directly

Common mistakes

  • Hard-coding month lengths

Follow-ups

  • How would you get the last day of the previous month?
  • How would you list all month ends in a year?

Tips

  • Go to the 1st before adding months