In PostgreSQL, we can use the -
operator to subtract one or more months from a date.
Examples
We can specify intervals when subtracting from dates. For example, we can use month
or months
to subtract one or more months from a date:
SELECT date '2040-03-18' - interval '1 month';
Result:
2040-02-18 00:00:00
And in plural form:
SELECT date '2040-03-18' - interval '6 months';
Result:
2039-09-18 00:00:00
Specified in Days
We can also use the equivalent number in days (or even weeks):
SELECT date '2040-06-20' - interval '31 days';
Result:
2040-05-20 00:00:00
We can also use an integer when specifying it in days:
SELECT date '2040-06-20' - 31;
Result:
2040-05-20
Or like this:
SELECT date '2040-06-20' - integer '31';
Result:
2040-05-20
Adding Negative Values
We can also add negative values to dates. In this case, we can use a negative value with the +
sign:
Example:
SELECT date '2040-06-20' + interval '-6 months';
Result:
2039-12-20 00:00:00
We can do the same thing with the integer option:
SELECT date '2040-06-20' + integer '-31';
Result:
2040-05-20