7

I need to find the account created for the current day, et for the last 7 days.

To find my results for today, it works, and I do this :

SELECT * FROM `account` where DATE(created_at) = DATE(NOW())

But I don't know how to do to get the last 7days account.

I tried something like this, but without success :

SELECT * FROM `account` where DATE(created_at) BETWEEN DATE(NOW()) AND DATE(NOW()-7)

Have you an idea ?

1

4 Answers 4

32

in mysql:

SELECT * FROM `account` 
WHERE DATE(created_at) > (NOW() - INTERVAL 7 DAY)
2
  • 6
    -1 This is not "between today and 7 days ago". This is "after 7 days ago" which may include future dates. Jun 8, 2011 at 10:20
  • 2
    if you have future dates in a column which should contain a date when something was created then something different is very wrong anyway. but you are right, better be safe than sorry.
    – Gryphius
    Jun 8, 2011 at 11:17
27

Try:

BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW()
2
  • @bahamut100: I recommend this answer over the accepted one. They are subtly different. Jun 8, 2011 at 11:17
  • 2
    +1 too. Plus this one does not have a huge performance penalty as the number of rows grow (compared to the accepted answer which uses a function on a column used in where)... Jul 13, 2011 at 12:30
3

If created_at has an index and you wouldn't like to prevent the optimiser from using it, I would recommend the following pattern (assuming created_at contains both date and time):

WHERE created_at >= CURRENT_DATE - INTERVAL 7 DAY
  AND created_at <  CURRENT_DATE + INTERVAL 1 DAY

This spans the range from the day exactly one week ago till today (inclusive), so 8 days in total.

0

also have a look at MySQL functions ADDDATE(), DATE_ADD(), DATE_SUB()

e.g.

ADDDATE(DATE(NOW()), -7)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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