Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select datetime field where date equals today

Tags:

I am trying to select a datetime field where the date equals today. However, the query never returns any rows.

I have this row in my database:

id    booked_at
1     2015-08-05 09:10:56

The query i'm using is:

select date(`booked_at`) from `booking_dates` where booked_at = CURDATE();

Why is this not returning the row above?

like image 385
V4n1ll4 Avatar asked Aug 05 '15 09:08

V4n1ll4


People also ask

How do you obtain today's date in MySQL?

MySQL CURDATE() Function The CURDATE() function returns the current date. Note: The date is returned as "YYYY-MM-DD" (string) or as YYYYMMDD (numeric).

How do I reference today's date in SQL?

To get the current date and time in SQL Server, use the GETDATE() function. This function returns a datetime data type; in other words, it contains both the date and the time, e.g. 2019-08-20 10:22:34 .

What function finds current time and date in MySQL?

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 can I compare current date and date in MySQL database?

MySQL has the ability to compare two different dates written as a string expression. When you need to compare dates between a date column and an arbitrary date, you can use the DATE() function to extract the date part from your column and compare it with a string that represents your desired date.


2 Answers

You have to strip the time part of booked_at because 2015-08-05 09:10:56 is not equal to 2015-08-05. Try this:

select date(booked_at) from booking_dates where date(booked_at) = CURDATE();
like image 136
Jan Avatar answered Sep 21 '22 15:09

Jan


To use index on column booked_at:

SELECT date(booked_at)
FROM booking_dates
WHERE booked_at >= CURDATE()
    AND booked_at < CURDATE() + INTERVAL 1 DAY
like image 38
miralong Avatar answered Sep 18 '22 15:09

miralong