← Back to SQL, page 8

sql-0156 · Medium mid

Write an expression that returns the last day of the month for any date.

Go to the first day of the month, add one month, and subtract one day. In SQLite: date(d, 'start of month', '+1 month', '-1 day'). In PostgreSQL: (date_trunc('month', d) + interval '1 month - 1 day')::date. Starting from the first of the month avoids month-length surprises.

Full answer
sql
WITH d(x) AS (VALUES ('2026-01-15'), ('2026-02-10'), ('2028-02-10'))
SELECT x, date(x, 'start of month', '+1 month', '-1 day') AS month_end
FROM d ORDER BY x;
xmonth_end
2026-01-152026-01-31
2026-02-102026-02-28
2028-02-102028-02-29

Because the calculation starts on the 1st, adding a month never hits a missing day, and subtracting one day lands on the month's end, including 29 February in leap years.

PostgreSQL:

sql
SELECT x, (date_trunc('month', x) + INTERVAL '1 month - 1 day')::date AS month_end
FROM (VALUES (DATE '2026-01-15'), (DATE '2026-02-10'), (DATE '2028-02-10')) AS d(x) ORDER BY x;
xmonth_end
2026-01-152026-01-31
2026-02-102026-02-28
2028-02-102028-02-29

The same building blocks give the first day of the next month ('start of month', '+1 month'), which is the right exclusive upper bound for "all rows in this month".

sql
WITH d(x) AS (VALUES ('2026-01-15'), ('2026-02-10'), ('2028-02-10'))
SELECT x, date(x, 'start of month', '+1 month', '-1 day') AS month_end
FROM d ORDER BY x;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • start of month, +1 month, -1 day
  • Starting from the 1st avoids normalization issues
  • Handles leap years automatically
  • The first of next month is a good exclusive bound

Common mistakes

  • Adding 30 days and calling it a month
  • Building month-end from the original day number

Follow-ups

  • How would you get the first Monday of a month?
  • How would you count business days in a month?

Tips

  • Explain why starting at the 1st is safe