📜  DATE_SUB postgres - SQL (1)

📅  最后修改于: 2023-12-03 15:30:22.888000             🧑  作者: Mango

DATE_SUB postgres - SQL

The DATE_SUB function in PostgreSQL is used to subtract an interval from a date or timestamp. This function is used to manipulate datetime values by adding or subtracting different intervals like minutes, hours, days, weeks, months, or years.

Syntax

The general syntax of the DATE_SUB function is as follows:

DATE_SUB(date, interval)

Here, date is the date or timestamp from which an interval must be subtracted, and interval is the value of the interval to subtract.

Example

To understand the DATE_SUB function in PostgreSQL, let’s consider an example where we need to subtract 1 day from the current date.

SELECT current_date - interval '1 day';

-- Output: 2021-09-13

In the above example, we have used the interval keyword to subtract a day from the current date.

Similarly, we can subtract different intervals using the DATE_SUB function. For example, let’s subtract 2 months from the current timestamp.

SELECT current_timestamp - interval '2 months';

-- Output: 2021-07-15 12:34:56.789

In the above example, we have used the current_timestamp function to get the current timestamp and subtracted 2 months using the interval keyword.

Conclusion

In conclusion, the DATE_SUB function in PostgreSQL is a powerful function that allows us to manipulate date and timestamp values by subtracting different intervals. By understanding its syntax and usage, we can easily apply this function in our SQL queries to perform various date and time-related computations.