Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do : "Between TODAY AND TODAY-7"?

Tags:

sql

mysql

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 ?

like image 342
bahamut100 Avatar asked Jun 08 '11 09:06

bahamut100


3 Answers

in mysql:

SELECT * FROM `account` 
WHERE DATE(created_at) > (NOW() - INTERVAL 7 DAY)
like image 87
Gryphius Avatar answered Nov 05 '22 13:11

Gryphius


Try:

BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW()
like image 31
Anne Avatar answered Nov 05 '22 14:11

Anne


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.

like image 3
Andriy M Avatar answered Nov 05 '22 13:11

Andriy M