MySQL – How to Select Data from 2 Days Ago

MySQL

Currently, I am running the following SQL (in MySQL) query to return the column for records recorded at 12am on the current day, up to the current time. So, if today is 2/3, and I run the query at 8pm, I will return all data recorded from 12:01am up to 8pm.

My question is; how do I retrieve yesterday's data? I want the same column, except instead of today's date, I want yesterday.

SELECT column1 
FROM db.table 
WHERE TS >= CURDATE() AND TS < CURDATE() + INTERVAL 1 DAY;

My second question is, how would I take the same column, and find the records for the entire month, up to the CURDATE()?

Best Answer

If the current WHERE condition specifies today and you want yesterday, then just subtract one day from both expressions. That will make the first expression CURDATE() - INTERVAL 1 DAY and the second simply CURDATE():

SELECT column1 
FROM db.table 
WHERE TS >= CURDATE() - INTERVAL 1 DAY AND TS < CURDATE();