You are on page 1of 16

DATE_SUB() Getting the recent one month or year records from

MySQL table
Syntax of DATE_SUB()

DATE_SUB(date, INTERVAL, expression, UNIT)

Example

SELECT DATE_SUB( '2016-12-25', INTERVAL 3 DAY )

Output is 2016-12-22

We have subtracted three days form the given date by using DATE_SUB() function. In place of DAY we can use Month, year,
hour, minute, second etc , here is the list.
unit Value Expected expr Format Example

DAY DAYS DATE_SUB( '2016-11-29', INTERVAL 10 DAY )

MONTH MONTHS DATE_SUB( '2015-11-20', INTERVAL 5 MONTH )

WEEK WEEKS DATE_SUB( '2016-08-20', INTERVAL 5 WEEK )

QUARTER QUARTERS DATE_SUB( '2016-08-20', INTERVAL 2 QUARTER )


YEAR YEARS DATE_SUB( '2016-02-23', INTERVAL 2 YEAR )

YEAR_MONTH 'YEARS-MONTHS' DATE_SUB( '2016-02-23', INTERVAL '2-5' YEAR_MONTH )

To use the above Examples add SELECT at left and run the query.

SELECT DATE_SUB( '2016-02-23', INTERVAL 2 YEAR ); // 2014-02-23

SELECT DATE_SUB( CURDATE(), INTERVAL 2 YEAR ); // 2018-02-23

The second query depends on the todays date, so your result will be different.

Some time we have to collect last 7 or 15 days or X days (or month, year or week) data from MySQL table.

Video Tutorial on Date Query using CURDATE, BETWEEN , YEAR, MONTH, DAYOFWEEK()

Records of different date ranges by using DATE_SUB(), CURDATE() and BETWEEN() q…


q…
As we are working on various date function considering todays date, take a fresh copy of SQL dump with date column filled
with future dates and past dates considering the todays date (date-lastweek-dump.php).

You may not get any record when searching for last 10 days record by using SQL dump of more than 10 days old. Use this
query to get the distribution of date from both sides of today's date.

SELECT MIN(date),MAX(date) FROM dt_table ;

For example let us find out who are the new members joined in our forum in last week. One shop may be interested in knowing
new products added in last one month. What are the books arrived in last one year. Here irrespective of the date values we
want the records of last X days from today, or we can say that the records between today and last X days ( month , year or
week) are required.

We will use the MySQL function CURDATE() (date-curdate.php) to get the today's date.

To get the difference in today date and previous day or month we have to use the MySQL function DATE_SUB

DATE_SUB is a MySQL function which takes date expression, the interval and the constant to return the date value for further
calculation.

Here are some sample queries on how to get the records as per requirements . �

Last 10 days records

select * from dt_table where `date` >= DATE_SUB(CURDATE(), INTERVAL 10 DAY)

The above query will return last 10 days records. Note that this query will return all future dates also. To exclude future dates
we have to modify the above command a little by using between query (sql_between.php) to get records. Here is the modified
one.

SELECT * FROM dt_table WHERE `date` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 10 DAY ) AND CURDATE( )
Present Month Records
Starting from 1st day of the current month till now.

SELECT * FROM `dt_table` WHERE date between DATE_FORMAT(CURDATE() ,'%Y-%m-01') AND CURDATE()

Present Year Records


Starting from 1st Jan of the current Year till now.

SELECT * FROM `dt_table` WHERE date between DATE_FORMAT(CURDATE() ,'%Y-01-01') AND CURDATE()

Last one month records


Let us try to get records added in last one month

SELECT * FROM dt_table where `date` >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)

Here also future records will be returned so we can take care of that by using BETWEEN (sql_between.php) commands if
required.

SELECT * FROM dt_table WHERE date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 MONTH) AND CURDATE();

Using Year
select * from dt_table WHERE `date` >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)

Using year with BETWEEN

SELECT * FROM dt_table WHERE date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND CURDATE();

Records of previous month of any year

SELECT * FROM dt_table WHERE MONTH( DATE ) = MONTH( DATE_SUB(CURDATE(),INTERVAL 1 MONTH ))

Records of previous month of same year

SELECT * FROM dt_table WHERE MONTH( DATE ) = MONTH( DATE_SUB(CURDATE(),INTERVAL 1 MONTH ))

AND

YEAR( DATE ) = YEAR( DATE_SUB(CURDATE( ),INTERVAL 1 MONTH ))

Note the difference between Last one month record and Previous month record

Records of two date ranges


We can collect records between a particular date ranges by using between command and DATE_SUB. Here are some queries
to generate records between two date ranges.
SELECT * FROM dt_table WHERE `date` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 3 MONTH ) AND DATE_SUB( CURDATE( ) ,
INTERVAL 0 MONTH )

This query will return records between last three months. This query again we will modify to get the records between three
moths and six months.

SELECT * FROM dt_table WHERE `date` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 6 MONTH ) AND DATE_SUB( CURDATE( ) ,
INTERVAL 3 MONTH )

Now let us change this to get records between 6 month and 12 month.

SELECT * FROM dt_table WHERE `date` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 12 MONTH ) AND DATE_SUB( CURDATE( )
,INTERVAL 6 MONTH )

With this you can understand how the records between a month range or a year range can be collected from a table. Note that
the months ranges are calculated starting from current day. So if we are collecting records of last three months and we are in
15th day of 9th month then records of 15th day of 6th month we will get but the records of 14th day of 6th month will be
returning on next query that is between 3 months and 6 months.

Records of present week


SELECT * FROM `dt_table` WHERE WEEKOFYEAR(date)=WEEKOFYEAR(CURDATE())

Records of previous week

SELECT * FROM `dt_table` WHERE WEEKOFYEAR(date)=WEEKOFYEAR(CURDATE())-1

Records of next week

SELECT * FROM `dt_table` WHERE WEEKOFYEAR(date)=WEEKOFYEAR(CURDATE())+1

Records of present week all working days ( Mon - Fri )

SELECT * FROM `dt_table` WHERE WEEKOFYEAR(date)=WEEKOFYEAR(CURDATE())

AND

WEEKDAY(date) BETWEEN 1 AND 5

Records of present week all working days till today

SELECT * FROM `dt_table`

WHERE WEEKOFYEAR( DATE ) = WEEKOFYEAR( CURDATE( ) )

AND WEEKDAY( DATE ) BETWEEN 1 AND WEEKDAY(CURDATE())


Generate Query by using dates from Calendar → (date-query-generator.php)

Exercise on DATE queries (sql_exercise-date.php)

Using Date and time Queries


Now let us calculate with Time
unit Value Expected expr Format

Example

MICROSECOND MICROSECONDS

DATE_SUB( '2016-02-23 20:55:58', INTERVAL 225 MICROSECOND )

SECOND SECONDS

DATE_SUB( '2016-02-23 20:55:58', INTERVAL 2 SECOND )

MINUTE MINUTES

DATE_SUB( '2016-02-23 20:55:58', INTERVAL 2 MINUTE )

HOUR HOURS

DATE_SUB( '2016-02-23 20:55:58', INTERVAL 5 HOUR )

SECOND_MICROSECOND 'SECONDS.

MICROSECONDS'
DATE_SUB( '2016-02-23 20:55:58', INTERVAL '1.543' SECOND_MICROSECOND )

MINUTE_MICROSECOND 'MINUTES:

SECONDS.

MICROSECONDS'

DATE_SUB

( '2016-02-23 20:55:58',

INTERVAL '5:2.743' MINUTE_MICROSECOND )

MINUTE_SECOND 'MINUTES:

SECONDS'

DATE_SUB( '2016-02-23 20:55:58', INTERVAL '5:2' MINUTE_SECOND )

HOUR_MICROSECOND 'HOURS:MINUTES:

SECONDS.

MICROSECONDS'

DATE_SUB( '2016-02-23 20:55:58', INTERVAL '5:2:1.249' HOUR_MICROSECOND)

HOUR_SECOND 'HOURS:MINUTES:

SECONDS'

DATE_SUB( '2016-02-23 20:55:58', INTERVAL '5:2:1' HOUR_SECOND )

HOUR_MINUTE 'HOURS:MINUTES'
DATE_SUB( '2016-02-23 20:55:52', INTERVAL '5:2' HOUR_MINUTE )

DAY_MICROSECOND 'DAYS HOURS:


MINUTES:

SECONDS.

MICROSECONDS'

DATE_SUB( '2016-02-23 20:55:52', INTERVAL '2 5:2:24.879' DAY_MICROSECOND

DAY_SECOND 'DAYS HOURS:


MINUTES:SECONDS'

DATE_SUB( '2016-02-23 20:55:52', INTERVAL '2 5:2:24' DAY_SECOND)

DAY_MINUTE 'DAYS HOURS:


MINUTES'

DATE_SUB( '2016-02-23 20:55:52', INTERVAL '2 5:2' DAY_MINUTE)

DAY_HOUR 'DAYS HOURS'

DATE_SUB( '2016-02-23 20:55:52', INTERVAL '2 5' DAY_HOUR)

Our sample table dt_table_tm stores login date with time in a field along with one more column showing event_id.

All records of Last 5 Hours


SELECT * FROM `dt_table_tm` WHERE tm>=DATE_SUB(NOW(), INTERVAL 5 HOUR)

All records of Last 48 Hours

SELECT * FROM `dt_table_tm` WHERE tm>=DATE_SUB(NOW(), INTERVAL 48 HOUR)

All records of 15 hours 12 minutes

SELECT * FROM `dt_table_tm` WHERE tm>=DATE_SUB(NOW() , INTERVAL '15:12' HOUR_MINUTE)

In place of NOW() (date-now.php) we can use specific date and time ( timestamp ) Note : While using date use the format
YYYY-mm-dd ( YEAR - Month - date) and while using time use HH:MM:SS ( Hour : Minutes : Seconds )

SELECT * FROM `dt_table_tm` WHERE tm >= DATE_SUB( '2018-08-10 11:50:00', INTERVAL '2:18:33' HOUR_SECOND )

All logins between 9 and 10 hours ( from 9 and 10 both inclusive till it is not 11 )

SELECT * FROM `dt_table_tm` WHERE HOUR(tm) between 9 and 10

All logins betwee 9 and 10 for a perticular month and year


SELECT * FROM `dt_table_tm` WHERE HOUR(tm) between 9 and 10 and MONTH(tm)=08 and year(tm)=2018

By Using date_format() (date_format.php)

SELECT * FROM `dt_table_tm` WHERE HOUR(tm) between 9 and 10 and date_format(tm,'%Y-%m')='2018-08'

All logins between 11 and 18 hours on a prticular day

SELECT * FROM `dt_table_tm` WHERE HOUR(tm) between 11 and 18 and date(tm)='2018-08-09'

All logins between two input times in hour : minutes : seconds on a perticular day

SELECT * FROM `dt_table_tm` WHERE date(tm)='2018-08-09' AND TIME(tm) BETWEEN TIME('9:00:00') AND TIME('10:15:0
0')

Counting logins at different hours in all days ( using GROUP BY (date-group-by.php) )

SELECT hour(tm) , count(event_id) FROM `dt_table_tm` group by HOUR(tm)

First Login ( tm ) of all days. We will use GROUP BY (sql_group_by.php) and MIN() (sql_min.php)
SELECT DATE(tm), MIN(tm),DATE_FORMAT(MIN(tm),'%H : %i :%s') time

FROM `dt_table_tm` GROUP BY DATE(tm)

First Login of all days after a particular hour. ( HOUR(tm) >16 )

SELECT DATE(tm), MIN(tm),DATE_FORMAT(MIN(tm),'%H : %i :%s') time

FROM `dt_table_tm` WHERE HOUR(tm) > 16 GROUP BY DATE(tm)

First login of all days after a particular HOUR Minutes and seconds.

SELECT DATE(tm), MIN(tm),DATE_FORMAT(MIN(tm),'%H : %i :%s') time

FROM `dt_table_tm` WHERE TIME(tm) > '16:01:00' GROUP BY DATE(tm)

Generate Query by selecting date and time → (date-query-generator-time.php)

Records of last working days of week


Now let us try a different requirement. How to get the records of the working days of the week so far ? If today is Thursday then
records from Monday to Thursday should be returned.

Records of working days of this week or previous week. → (date-dayofweek.php)


Dynamic SQL dump query
To test above queries you need to have records of last 15 days or last 6 months ( or 12 Months ). Any dump created today will
not work in future dates ( say after 8 months ) . So to use above query which involves last 15 days or last 12 months records,
we have to generate dump file every day.

For the SQL with date and time , another table dt_table_tm is used and the dump file can be used .

SQL dump file generated based on date & time to test queries → (date-lastweek-dump.php)

← SQL Date References (date.php)


Records between two dates → (between-date.php)

(http://www.facebook.com/share.php?u=https://www.plus2net.com/sql_tutorial/date-lastweek.php)

This article is written by plus2net.com team.


https://www.plus2net.com

Subscribe
* indicates required
Email Address *
First Name

Last Name

Subscribe to plus2net

Subscribe

You might also like