Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Return Today's Records Using DATE from DATETIME Field

I have a table called "actions" with a DATETIME column called "occurred". I'm trying to return the records for today by doing the following

SELECT * FROM `actions` WHERE `occurred` = DATE(NOW());

But I get an empty result set. If I take the WHERE clause out, I can see all 295 rows in the table and there's at least 30 rows from today. Later I will be writing another query to return all records between today's date and X amount of days in the past but before I can get there I need to know why this query is returning an empty result set.

Thanks in advance.

like image 352
rws907 Avatar asked Oct 22 '12 02:10

rws907


People also ask

How do you obtain today's date in MySQL?

Simply use the CURDATE() function to get the current date. The date can be displayed in two different formats: ' YYYY-MM-DD ' if it is used in a string context or YYYYMMDD if it is used in a numeric context. There are two other functions that can be used instead of CURDATE() : CURRENT_DATE and CURRENT_DATE() .

What MySQL function returns the current date and time?

MySQL NOW() Function The NOW() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH-MM-SS" (string) or as YYYYMMDDHHMMSS. uuuuuu (numeric).

How do I get just the date from a timestamp?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column.


2 Answers

SELECT * FROM actions WHERE DATE(ocurred) = CURDATE();

DATE(ocurred) ignores the time part.

Here's the SQL Fiddle to play with the data: http://www.sqlfiddle.com/#!2/81708/2

like image 57
Leniel Maccaferri Avatar answered Nov 07 '22 22:11

Leniel Maccaferri


If there in no future date in occurred, you could just use below:

SELECT * FROM `actions` WHERE `occurred` > DATE_SUB(CURDATE(), INTERVAL 1 DAY);
like image 42
xdazz Avatar answered Nov 07 '22 22:11

xdazz