When you need to subtract 30 days from the current date and time in MySQL, you can use the DATE_SUB() function or directly use the INTERVAL expression. Here are two methods illustrated below:
Method 1: Using DATE_SUB() Function
The DATE_SUB() function subtracts a specified time interval from a given date. Its basic syntax is:
sqlDATE_SUB(date, INTERVAL expr type)
dateis the starting dateexpris the amount to subtracttypeis the time unit, such as DAY, MONTH, or YEAR.
For example, to subtract 30 days from the current date, use the following SQL query:
sqlSELECT DATE_SUB(NOW(), INTERVAL 30 DAY);
Method 2: Using INTERVAL Expression
You can directly apply the - INTERVAL expression to subtract a specific time from a date. For instance, subtracting 30 days is written as:
sqlSELECT NOW() - INTERVAL 30 DAY;
This method is straightforward and concise, making it convenient for simple date and time operations.
Example Application Scenario
Suppose you manage an online store and need to query orders from the past 30 days. Use the following SQL query:
sqlSELECT * FROM orders WHERE order_date >= NOW() - INTERVAL 30 DAY;
In this example, the second method is used to obtain the date 30 days ago from the current timestamp, filtering orders within the last 30 days.