How to grab the last x days in MySQL Table

Hi. I have a very simple task of grabbing the data for the past 7 days. My current query looks like this:

select * from `table`
where `date` > CURDATE() -7

This works perfectly well, only when we get to the next month it is not grabbing any day from the previous month. I need to grab the data regardless of what month it is, just the last 7 days. I can't find the right syntax for this.

Thank you in advance!

Answers

  • MarkSnodgrass
    MarkSnodgrass Portland, Oregon 🥷

    MySQL has a DATE_SUB function that would work for this. Try this for your where clause:

    WHERE `date` > DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)

    **Make sure to <3 any users posts that helped you.
    **Please mark as accepted the ones who solved your issue.
  • @Mark It works! Thank you very much!

  • GrantSmith
    GrantSmith Indiana 🥷

    Your version is close you just need to specify your units (day intervals):

    select * from `table`
    where `date` > CURDATE() - INTERVAL 7 DAY
    
    


    DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)
    

    and

    CURDATE() - INTERVAL 7 DAY
    

    are functionally the same. Also CURDATE and CURRENT_DATE are the same, they just have different names.



    **Was this post helpful? Click Agree or Like below**

    **Did this solve your problem? Accept it as a solution!**