Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Date Subtraction: How to Subtract Dates

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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, or TIMESTAMPTZ data type.

Step-by-Step

  1. Identify your base date: Determine which column or static date you are starting from. For example, if you have a table called orders with a column order_date, that is your base.
  2. Define the interval to subtract: Decide the unit of time you want to remove. PostgreSQL uses the INTERVAL keyword followed by a string describing the duration. Common intervals include:
    • '1 day'
    • '2 weeks'
    • '3 months'
    • '1 year'
    • '5 hours'
  3. Apply the subtraction operator: Use the minus sign (-) between your date and the interval.
    Example: SELECT order_date - INTERVAL '7 days' FROM orders;
  4. Cast the result (Optional): Subtracting an interval from a DATE often converts the result into a TIMESTAMP. 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;
  5. 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 - INTERVAL syntax.
  • 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 DATE from another DATE (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 the INTERVAL keyword.
  • 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 requires UTC normalization.

Tips

  • Use shorthand for days: While INTERVAL '1 day' is explicit, you can subtract an integer directly from a DATE type to remove days. For example, CURRENT_DATE - 7 will subtract 7 days. This only works for the DATE type, not TIMESTAMP.
  • 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:

  1. Check Data Types: Ensure the column you are subtracting from is actually a DATE or TIMESTAMP. Use \d table_name in psql to verify. If it is a string (VARCHAR), cast it first: column_name::date - INTERVAL '1 day'.
  2. Verify Syntax: Ensure you have the word INTERVAL before the string. A common error is writing date - '1 day', which will fail because PostgreSQL doesn't know if the string represents a date or a duration.
  3. Check for Nulls: If the result is NULL, check if the base date column contains NULL values. Any arithmetic operation involving NULL results in NULL. Use COALESCE(order_date, CURRENT_DATE) to provide a fallback.
  4. Review Casting: If the output format looks strange (e.g., including 00:00:00 time), add ::date to 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.