Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Is The Optimal Way To Select Rows From Last 7 Days?

What's the best way to select only those rows from the table that have been created in last 7 days?

There are dozens of time and date functions in MySQL and I'm a little bit confused about what's the easiest way to do this.

For the sake of this question, assume that you have a table called "my_table" and it contains a row "created_at" which is a DATETIME.

SELECT * FROM my_table WHERE ...

What would you fill in the WHERE clause?

like image 508
Richard Knop Avatar asked Nov 27 '22 02:11

Richard Knop


1 Answers

WHERE DATEDIFF(NOW(), created_at) <= 7;

I like it because it reads: "Where the Difference in Date between Now and when it was created is at most 7 (days)." in my own head

like image 176
Drew Avatar answered Dec 10 '22 07:12

Drew