MySQL time calculation function sql Date_sub () usage

Source: Internet
Author: User

This article for Bo Master original, without permission not reproduced:

When writing SQL, you often have to pass the value time in SQL, calculate and filter the time. Before the time is calculated in the background, direct value to SQL,

Today we found that there is a more convenient SQL function that simplifies a lot of code. This function is Date_sub ().

Date_sub will subtract a time value (time interval) from a date/time value.

The usage expression in its function is: date_sub (date,interval expr type),

The parameters of type can be of types:

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

Examples of use are:

-- a year ago  select  date_sub (Curdate (), INTERVAL 1  year) as   yeartime -- a day ago  select  Date_sub (Curdate (), INTERVAL 1  day) as  Span style= "COLOR: #000000" > selecttime -- month ago  select  Date_sub (Curdate (), INTERVAL 1  MONTH) as  Span style= "COLOR: #000000" > selecttime -- three year ago  select  Date_sub (Curdate (), INTERVAL 3  year) as  Yeartime 
    1. SELECT date_sub (' 2010-08-12 ', INTERVAL 3 day) as Newdate

Results: 2010-08-09

2.SELECT date_sub (' 2010-08-12 ', INTERVAL ' 3-2 ' Year_month) as Newdate

Results: 2007-06-12

3.SELECT date_sub (' 2011-09-14 2:44:36 ', INTERVAL ' 2:26 ' Hour_minute) as Newdate

Result: 2011-09-14 00:18:36

MySQL time calculation function sql Date_sub () usage

Related Article

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.