In PostgreSQL, we can use the +
operator to add one or more months to a date. There are several options when it comes to specifying the actual number of months.
Examples
Postgres allows us to specify intervals when adding to dates. We can therefore specify month
or months
:
SELECT date '2030-01-20' + interval '1 month';
Result:
2030-02-20 00:00:00
And in plural form:
SELECT date '2030-01-20' + interval '6 months';
Result:
2030-07-20 00:00:00
Specified in Days
We can also use the equivalent number in days (or weeks for that matter):
SELECT date '2030-01-20' + interval '31 days';
Result:
2030-02-20 00:00:00
Obviously, whether or not this matches the exact number of months will depend on the actual number of days or weeks specified.
We can alternatively use an integer when specifying it in days:
SELECT date '2030-01-20' + 31;
Result:
2030-02-20
We can also do it like this:
SELECT date '2030-01-20' + integer '31';
Result:
2030-02-20
Negative Values
We can also perform date arithmetic with negative values. If we use a negative value with the +
sign, then the specified number of months will be subtracted from the date. But if we use it with the -
sign, then it will be added to the date.
Example:
SELECT date '2030-01-20' - interval '-6 months';
Result:
2030-07-20 00:00:00
We can do the same thing with the integer option:
SELECT date '2030-01-20' - integer '-181';
Result:
2030-07-20