MySQL Query – Get Content from Last 7 Days

MySQL

I thought I was good with SQL till I was told to get the content of all 30 days. I do have a column called "connect_time" which has date and time in the following format: 2014-08-28 11:11:42

All my queries have been a fail till now. I tried the following https://stackoverflow.com/questions/13266130/how-to-select-last-one-week-data-from-todays-date

I just tried:

SELECT  *
FROM   Table_Name
WHERE  connect_time >= DATEADD(day,-7, GETDATE())

I cannot understand the reason its wrong and I am trying to find the syntax so I can edit it myself but I am getting confused what part of the code is syntax and what is their column names.

Best Answer

Using DATE_ADD() or DATE_SUB()

SELECT * FROM Table_Name
WHERE connect_time >= DATE_ADD(CURDATE(),INTERVAL -7 DAY);

or

SELECT * FROM Table_Name
WHERE connect_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY);

Without those functions, you can also do

SELECT * FROM Table_Name
WHERE connect_time >= (CURDATE() + INTERVAL -7 DAY);

or

SELECT * FROM Table_Name
WHERE connect_time >= (CURDATE() - INTERVAL 7 DAY);