MySQL selecting items between two dates and times

Viewed 36

I'm trying to create a query where I select the items from yesterday at 9:00 am until today 9:00 am. Is there any way to do it without needing to put the yesterday's date and today's date?

Something like this:

SELECT title 
  FROM table_name 
 WHERE date >= YESTERDAY(9:00:00) 
   AND date <= TODAY(9:00:00);
1 Answers

You may try using:

SELECT title
FROM table_name
WHERE
    date >= DATE_SUB(TIMESTAMP(CURDATE()), INTERVAL 15 HOUR) AND
    date <= DATE_ADD(TIMESTAMP(CURDATE()), INTERVAL 9 HOUR);

The logic here is that TIMESTAMP(CURDATE()) gives today at midnight. Therefore, 9am on the previous day is 15 hours before this point in time, while 9am of today is 9 hours past this time.

Related