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?
MySQL CURDATE() Function The CURDATE() function returns the current date. Note: The date is returned as "YYYY-MM-DD" (string) or as YYYYMMDD (numeric).
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 .
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).
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.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With