date_sub function in MySQL

Source: Internet
Author: User

When querying a query or a menu, you often want to query for a specified time or time period, for example, to query for information within one day, to query for information within a week, to query within one months.

Define and use the Date_sub () function to subtract a specified time interval from a date.
1. Syntax
Date_sub (Date,interval expr type)
DateThe argument is a valid date expression. ExprParameters are the interval of time that you want to add.
The type parameter can be the following value:
Type value
Microsecond
SECOND
MINUTE
HOUR
Day
WEEK
MONTH
QUARTER
Year
Second_microsecond
Minute_microsecond
Minute_second
Hour_microsecond
Hour_second
Hour_minute
Day_microsecond
Day_second
Day_minute
Day_hour
Year_month
A simple example assumes that we have the following table:

OrderId ProductName OrderDate
1 ' Computer ' 2012-12-29 16:25:46.635
Now, we want to subtract 2 days from "OrderDate".
We use the following SELECT statement:
SELECT Orderid,date_sub (Orderdate,interval 2 day) as Orderpaydate from  Orders  
Results:
OrderId orderpaydate
1 2012-12-27 16:25:46.635
3. Complex examples:

Query Day:
SELECT * FROM table where to_days (column_time) = To_days (now ());
SELECT * FROM table where date (column_time) = Curdate ();
Query one week:
SELECT * FROM table where Date_sub (Curdate (), INTERVAL 7 day) <= DATE (column_time);
Query one months:
SELECT * FROM table where Date_sub (Curdate (), INTERVAL 1 MONTH) <= DATE (column_time);
Query a specified number of days
SELECT * FROM table where Date_sub (Curdate (), INTERVAL 2 day) <= DATE (column_time);
We can use the unused type, for example, if we want to query the order within two weeks, and we can say so.
It's so simple.

date_sub function in MySQL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.