67

I imagine this is pretty simple, but can't figure it out. I'm trying to make a few pages - one which will contain results selected from my mysql db's table for today, this week, and this month. The dates are entered when the record is created with date('Y-m-d H:i:s');. Here's what I have so far:

day where date>(date-(60*60*24))

 "SELECT * FROM jokes WHERE date>(date-(60*60*24)) ORDER BY score DESC"

week where date>(date-(60*60*24*7))

 "SELECT * FROM jokes WHERE date>(date-(60*60*24*7)) ORDER BY score DESC"

month (30 days) where date>(date-(60*60*24*30))

 "SELECT * FROM jokes WHERE date>(date-(60*60*24*30)) ORDER BY score DESC"

Any ideas would be much appreciated. Thanks!

13 Answers 13

126

Assuming your date column is an actual MySQL date column:

SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY score DESC;        
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY score DESC;
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY score DESC;
10
  • 1
    So I changed it to datetime and didn't do anything and it works. Thanks very much! Mar 13, 2011 at 23:39
  • 1
    @NathanOstgard I am trying the same query for a month...but adding another AND and its not working...like this: SELECT id,title,start_date FROM events WHERE start_date > DATE_SUB(NOW(), INTERVAL 1 MONTH) AND city = 'Khobar' ORDER BY start_date DESC....any idea why?
    – sys_debug
    Aug 2, 2012 at 9:07
  • 1
    Wouldn't this cause a floating result set, for instance if you subtract 1 day from now, it will be a different result set at 2am as compared to the result set from 8pm? Jul 25, 2013 at 23:53
  • 3
    This will just subtract 1 week right? What about the current week?
    – C4d
    Aug 24, 2015 at 6:51
  • 1
    I'm confused: does this actually show the data for THIS week or MAX 1 week ago?
    – qwertzman
    Aug 21, 2017 at 13:26
74

Try using date and time functions (MONTH(), YEAR(), DAY(), MySQL Manual)

This week:

SELECT * FROM jokes WHERE WEEKOFYEAR(date)=WEEKOFYEAR(NOW());

Last week:

SELECT * FROM jokes WHERE WEEKOFYEAR(date)=WEEKOFYEAR(NOW())-1;
5
  • 1
    It must do a cast internally because this just kills performance on large result sets. Jul 25, 2013 at 23:57
  • 1
    What happends if the current week is week 1? does it automaticly take the last week of the previous year? Jul 2, 2015 at 12:52
  • this is the best answer by far
    – krummens
    Oct 12, 2015 at 16:54
  • 3
    The best answer, please update it to SELECT * FROM jokes WHERE WEEKOFYEAR(date)=WEEKOFYEAR(NOW()) AND YEAR(date) = YEAR(now()); to exclude older years' data. Sep 20, 2016 at 21:04
  • Thanks mate, this is the most correct way to do it.
    – Amit Kumar
    May 2, 2018 at 9:41
40

Current month:

SELECT * FROM jokes WHERE YEAR(date) = YEAR(NOW()) AND MONTH(date)=MONTH(NOW());

Current week:

SELECT * FROM jokes WHERE WEEKOFYEAR(date) = WEEKOFYEAR(NOW());

Current day:

SELECT * FROM jokes WHERE YEAR(date) = YEAR(NOW()) AND MONTH(date) = MONTH(NOW()) AND DAY(date) = DAY(NOW());

This will select only current month, really week and really only today :-)

2
  • 2
    Thanks very much. This solution worked perfect for me when creating some custom leader boards.
    – Bonxy
    Mar 12, 2015 at 0:10
  • 1
    For current week use YEARWEEK, because if you have data in your table from year 2016, 2017 and 2018 with the same week date for example, it will only show the 2018 week data. With WEEKOFYEAR it will show week data from 2016, 2017 and 2018.
    – mattja
    Feb 21, 2018 at 5:23
9

Nathan's answer will give you jokes from last 24, 168, and 744 hours, NOT the jokes from today, this week, this month. If that's what you want, great, but I think you might be looking for something different.

Using his code, at noon, you will get the jokes beginning yesterday at noon, and ending today at noon. If you really want today's jokes, try the following:

SELECT * FROM jokes WHERE date >= CURRENT_DATE() ORDER BY score DESC;  

You would have to do something a little different from current week, month, etc., but you get the idea.

4

Everybody seems to refer to date being a column in the table.
I dont think this is good practice. The word date might just be a keyword in some coding language (maybe Oracle) so please change the columnname date to maybe JDate.
So will the following work better:

SELECT * FROM jokes WHERE JDate >= CURRENT_DATE() ORDER BY JScore DESC;

So we have a table called Jokes with columns JScore and JDate.

3

A better solution for "today" is:

SELECT * FROM jokes WHERE DATE(date) = DATE(NOW())
2

Nathan's answer is very close however it will return a floating result set. As the time shifts, records will float off of and onto the result set. Using the DATE() function on NOW() will strip the time element from the date creating a static result set. Since the date() function is applied to now() instead of the actual date column performance should be higher since applying a function such as date() to a date column inhibits MySql's ability to use an index.

To keep the result set static use:

SELECT * FROM jokes WHERE date > DATE_SUB(DATE(NOW()), INTERVAL 1 DAY) 
ORDER BY score DESC;

SELECT * FROM jokes WHERE date > DATE_SUB(DATE(NOW()), INTERVAL 1 WEEK) 
ORDER BY score DESC;

SELECT * FROM jokes WHERE date > DATE_SUB(DATE(NOW()), INTERVAL 1 MONTH) 
ORDER BY score DESC;
1
  • 2
    Yes, but this is still not this week - if week starts on monday, and we will do this select in tuesday, we will get jokes from last tuesday (last week), not this monday, cause this is this week by right logic. May 22, 2014 at 8:29
1

I think using NOW() function is incorrect for getting time difference. Because by NOW() function every time your are calculating the past 24 hours. You must use CURDATE() instead.

    function your_function($time, $your_date) {
    if ($time == 'today') {
        $timeSQL = ' Date($your_date)= CURDATE()';
    }
    if ($time == 'week') {
        $timeSQL = ' YEARWEEK($your_date)= YEARWEEK(CURDATE())';
    }
    if ($time == 'month') {
        $timeSQL = ' Year($your_date)=Year(CURDATE()) AND Month(`your_date`)= Month(CURDATE())';
    }

    $Sql = "SELECT * FROM jokes WHERE ".$timeSQL
    return $Result = $this->db->query($Sql)->result_array();
}
0

Well, this solution will help you select only current month, current week and only today

SELECT * FROM games WHERE games.published_gm = 1 AND YEAR(addedon_gm) = YEAR(NOW()) AND MONTH(addedon_gm) = MONTH(NOW()) AND DAY(addedon_gm) = DAY(NOW()) ORDER BY addedon_gm DESC;

For Weekly added posts:

WEEKOFYEAR(addedon_gm) = WEEKOFYEAR(NOW())

For Monthly added posts:

MONTH(addedon_gm) = MONTH(NOW())

For Yearly added posts:

YEAR(addedon_gm) = YEAR(NOW())

you'll get the accurate results where show only the games added today, otherwise you may display: "No New Games Found For Today". Using ShowIF recordset is empty transaction.

1
  • 1
    Please explain your solution - don't just post code. Dec 8, 2015 at 19:31
0

To get last week's data in MySQL. This works for me even across the year boundries.

select * from orders_order where YEARWEEK(my_date_field)= YEARWEEK(DATE_SUB(CURRENT_DATE(), INTERVAL 1 WEEK));

To get current week's data

select * from orders_order where YEARWEEK(date_sold)= YEARWEEK(CURRENT_DATE());
0

I suggest you to do like that:

SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY score DESC;        
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY score DESC;
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY score DESC;
1
  • Just to add here that: this query works fine but it does not get data from current week like if today is Tuesday then it should only show data of Monday and Tuesday but it fetches for last 7 days.
    – jazeb007
    Aug 2, 2022 at 19:29
0

SELECT sum(if(DATE(dDate)=DATE(CURRENT_TIMESTAMP),earning,null)) astodays, sum(if(YEARWEEK(dDate)=YEARWEEK(CURRENT_DATE),earning,null)) as weeks, IF((MONTH(dDate) = MONTH(CURRENT_TIMESTAMP()) AND YEAR(dDate) = YEAR(CURRENT_TIMESTAMP())),sum(earning),0) AS months, IF(YEAR(dDate) = YEAR(CURRENT_TIMESTAMP()),sum(earning),0) AS years, sum(fAdminFinalEarning) as total_earning FROM earning

1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jul 1, 2022 at 3:07
-1

You can do same thing using single query

SELECT sum(if(DATE(dDate)=DATE(CURRENT_TIMESTAMP),earning,null)) astodays,
       sum(if(YEARWEEK(dDate)=YEARWEEK(CURRENT_DATE),earning,null)) as weeks, 
       IF((MONTH(dDate) = MONTH(CURRENT_TIMESTAMP()) AND YEAR(dDate) = YEAR(CURRENT_TIMESTAMP())),sum(earning),0) AS months,
       IF(YEAR(dDate) = YEAR(CURRENT_TIMESTAMP()),sum(earning),0) AS years, 
       sum(fAdminFinalEarning) as total_earning FROM `earning`

Hope this works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.