We can subtract one or more days from a date in PostgreSQL with the -
operator.
Examples
The simplest way to subtract one or more days from a date is to use an integer, like this:
SELECT date '2022-10-12' - 7;
Result:
2022-10-05
Or like this:
SELECT date '2022-10-12' - integer '7';
Result:
2022-10-05
Using Intervals
We can also specify intervals when subtracting from dates. To subtract days, we can use day
or days
:
SELECT date '2022-10-12' - interval '1 day';
Result:
2022-10-11 00:00:00
And in plural form:
SELECT date '2022-10-12' - interval '7 days';
Result:
2022-10-05 00:00:00
Specified in Hours
Another way to do it is to specify the number in its hourly equivalent:
SELECT date '2022-10-12' - interval '24 hours';
Result:
2022-10-11 00:00:00
Adding Negative Values
We can also add negative values to dates. To subtract a negative amount, we can use the negative value with the +
sign:
Example:
SELECT date '2022-10-12' + interval '-7 days';
Result:
2022-10-05 00:00:00
We can do the same thing with the integer option:
SELECT date '2022-10-12' + integer '-7';
Result:
2022-10-05