PostgreSQL Date Subtraction: How to Subtract Dates
In this article
PostgreSQL does not have a single function named date_subtract(); instead, it uses the subtraction operator (-) combined with the INTERVAL data type to subtract time from a date. To subtract a specific amount of time from a date, you subtract an INTERVAL value (e.g., '1 day'::interval) from a DATE or TIMESTAMP column.
What You'll Need
- A PostgreSQL database instance.
- A client tool to execute queries (such as pgAdmin, psql, or DBeaver).
- A table containing a column with a
DATE,TIMESTAMP, orTIMESTAMPTZdata type.
Step-by-Step
- Identify your base date: Determine which column or static date you are starting from. For example, if you have a table called
orderswith a columnorder_date, that is your base. - Define the interval to subtract: Decide the unit of time you want to remove. PostgreSQL uses the
INTERVALkeyword followed by a string describing the duration. Common intervals include:'1 day''2 weeks''3 months''1 year''5 hours'
- Apply the subtraction operator: Use the minus sign (
-) between your date and the interval.
Example:SELECT order_date - INTERVAL '7 days' FROM orders; - Cast the result (Optional): Subtracting an interval from a
DATEoften converts the result into aTIMESTAMP. If you only need the date portion, cast the result back to a date using::date.
Example:SELECT (order_date - INTERVAL '7 days')::date FROM orders; - Execute the query: Run your SQL statement in your editor to verify the output. For a static date, you can test it like this:
SELECT CURRENT_DATE - INTERVAL '1 month';
Common Mistakes
- Using non-existent functions: Attempting to call
DATE_SUB()(which is a MySQL function) will result in a "function does not exist" error in PostgreSQL. Always use the- INTERVALsyntax. - Forgetting single quotes: The interval value must be wrapped in single quotes (e.g.,
'1 day'). Using double quotes or no quotes will cause a syntax error. - Confusing Date vs. Integer subtraction: If you subtract one
DATEfrom anotherDATE(e.g.,date_a - date_b), PostgreSQL returns an integer representing the number of days between them. If you want to subtract a duration from a date, you must use theINTERVALkeyword. - Ignoring Time Zones: When working with
TIMESTAMP WITH TIME ZONE, subtracting intervals can occasionally produce unexpected results during Daylight Savings Time transitions. Always verify if your application requiresUTCnormalization.
Tips
- Use shorthand for days: While
INTERVAL '1 day'is explicit, you can subtract an integer directly from aDATEtype to remove days. For example,CURRENT_DATE - 7will subtract 7 days. This only works for theDATEtype, notTIMESTAMP. - Combine intervals: You can subtract complex durations by combining units within the interval string. For example:
INTERVAL '1 year 2 months 5 days'. - Use positive intervals for subtraction: To subtract, use the minus sign with a positive interval (
- INTERVAL '1 day'). Alternatively, you can use a plus sign with a negative interval (+ INTERVAL '-1 day'), though the former is more readable. - Dynamic Intervals: If the amount to subtract is stored in another column, use the
make_interval()function or multiply the interval by the column value:order_date - (days_to_subtract * INTERVAL '1 day').
Troubleshooting
If your query does not go to plan, try these steps in order:
- Check Data Types: Ensure the column you are subtracting from is actually a
DATEorTIMESTAMP. Use\d table_namein psql to verify. If it is a string (VARCHAR), cast it first:column_name::date - INTERVAL '1 day'. - Verify Syntax: Ensure you have the word
INTERVALbefore the string. A common error is writingdate - '1 day', which will fail because PostgreSQL doesn't know if the string represents a date or a duration. - Check for Nulls: If the result is
NULL, check if the base date column containsNULLvalues. Any arithmetic operation involvingNULLresults inNULL. UseCOALESCE(order_date, CURRENT_DATE)to provide a fallback. - Review Casting: If the output format looks strange (e.g., including 00:00:00 time), add
::dateto the end of the expression to strip the time component.
Frequently Asked Questions
How do I subtract 30 days from a date in PostgreSQL?
The most reliable way is to use SELECT your_date_column - INTERVAL '30 days';. If the column is specifically a DATE type, you can also use SELECT your_date_column - 30;.
What is the difference between subtracting a date and an interval?
Subtracting a date from another date (Date A - Date B) returns an integer representing the number of days. Subtracting an interval from a date (Date A - Interval B) returns a new date or timestamp.
Can I subtract months or years specifically?
Yes. Use INTERVAL '1 month' or INTERVAL '1 year'. PostgreSQL automatically handles the varying number of days in different months and leap years.
How do I subtract a dynamic number of days from a column?
If you have a column called days_offset, use the multiplication syntax: SELECT base_date - (days_offset * INTERVAL '1 day') FROM table;
Does subtracting an interval change the data type?
Yes, subtracting an INTERVAL from a DATE usually results in a TIMESTAMP. To keep it as a DATE, wrap the operation in parentheses and cast it: (date_col - INTERVAL '1 day')::date.