Date Plus Month Interval Clamps Overflow
Adding one month clamps to the month's last day, so Jan 31 becomes Feb 28 and repeated monthly arithmetic drifts unless each cycle uses a fixed base.
Code
-- 加一个月不是"加 30 天":目标月没有 31 号时收口到该月最后一天
SELECT DATE '2026-01-31' + INTERVAL '1 month' AS feb; -- 2026-02-28 00:00:00
SELECT DATE '2026-03-31' + INTERVAL '1 month' AS apr; -- 2026-04-30 00:00:00
-- 逐月反复累加会漂移:31 号 → 28 号 → 28 号 → 28 号
SELECT DATE '2026-01-31' + INTERVAL '1 month' + INTERVAL '1 month' AS drifted;
-- 固定基准 + n 个月不漂移,但溢出日仍会收口
SELECT n,
(DATE '2026-01-31' + (n * INTERVAL '1 month'))::date AS cycle
FROM generate_series(0, 3) AS n;
-- timestamptz 同样按月收口,时间部分原样保留
SELECT TIMESTAMPTZ '2026-01-31 12:00:00+00' + INTERVAL '1 month';
-- 需要"每月 31 号"固定账期语义时,在应用层按年月构造日期,
-- 不要在循环里对上月结果反复 + 1 monthHow the snippet works
What runs here is SELECT — generate_series are the objects involved.
Applying it
The generate_series table is the working surface here.
Statements that matter
SELECT n,
(DATE '2026-01-31' + (n * INTERVAL '1 month'))::date AS cycle
FROM generate_series(0, 3) AS n;
SELECT DATE '2026-01-31' + INTERVAL '1 month' AS feb; -- 2026-02-28 00:00:00
SELECT DATE '2026-03-31' + INTERVAL '1 month' AS apr; -- 2026-04-30 00:00:00
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.
FAQ
- Which objects does the SQL touch?
- The references are `generate_series`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.