Get the same day in the previous month in SQL
Month-over-month comparisons compare 'the 15th of this month' with 'the 15th of last month', not with '31 days ago'.
The task
Subtracting an interval of one month does calendar-aware month arithmetic, not a fixed 30 days.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
SELECT
d - interval '1 month' AS prev_month_same_day,
(date_trunc('month', d) - interval '1 day')::date AS prev_month_end
FROM (SELECT DATE '2026-03-31' AS d) x;
작동 방식
Subtracting interval '1 month' keeps the day number and rewinds the month. When the day does not exist (March 31 minus one month), PostgreSQL clamps to the last day of the target month, here 2026-02-28. SQL Server's DATEADD and MySQL's INTERVAL arithmetic clamp the same way. The result is a timestamp on PostgreSQL; cast it with ::date if you need a date. The second expression gives the previous month's end for month-to-month totals.
Variations
SQL Server
SQL ServerSELECT
DATEADD(MONTH, -1, d) AS prev_month_same_day,
EOMONTH(d, -1) AS prev_month_end
FROM (SELECT CAST('2026-03-31' AS DATE) AS d) x;
MySQL
MySQLSELECT
d - INTERVAL 1 MONTH AS prev_month_same_day,
LAST_DAY(d - INTERVAL 1 MONTH) AS prev_month_end
FROM (SELECT CURDATE() AS d) x;
Questions that come up
Why not just subtract 30 days?
Thirty days drifts: March 31 minus 30 days is March 1, still in the same month, because months run 28 to 31 days. Calendar-aware subtraction (interval '1 month', DATEADD(MONTH, -1, ...)) lands in the previous month every time.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.