MY query looks like this:
SELECT COUNT(entryID)
FROM table
WHERE date >= DATE_SUB(CURDATE(), INTERVAL 1 DAY)
Will this count the rows whose date
values are within the day (starting at 12:00; not within 24 hours)? If not, how do I do so?
MY query looks like this:
SELECT COUNT(entryID)
FROM table
WHERE date >= DATE_SUB(CURDATE(), INTERVAL 1 DAY)
Will this count the rows whose date
values are within the day (starting at 12:00; not within 24 hours)? If not, how do I do so?
The following should be enough to get records within the current day:
SELECT COUNT(entryID)
FROM table
WHERE date >= CURDATE()
As Michael notes in the comments, it looks at all records within the last two days in its current form.
The >=
operator is only necessary if date
is actually a datetime
- if it's just a date
type, =
should suffice.
DATE(date)
to get just the date part, though). –
Thomson =
should be enough then, and actually more correct in case there were ever future dates in there. –
Displeasure DATE(date)
will stop indexes on row date
from working. Would it work for me to use WHERE date >= CURDATE()
even when date
is DATETIME
? Will it still only get rows from the very beginning of the day? –
Thomson date
might be datetime
. –
Displeasure Here's the solution:
SELECT COUNT(entryID)
FROM table
WHERE DATE(date) >= CURDATE()
Since my date
column is type DATETIME
, I use DATE(date)
to just get the date part, not the time part.
SELECT DATE_FORMAT(NOW(), "%Y-%m-%d 00:00:00");
Output today's start time
WHERE date >= DATE_FORMAT(NOW(), "%Y-%m-%d 00:00:00")
CURDATE() returns a date like '2012-03-30', not a timestamp like '2012-03-30 21:38:17'. The subtraction of one day also returns just a date, not a timestamp. If you want to think of a date as a timestamp think of it as the beginning of that day, meaning a time of '00:00:00'.
And this is the reason, why this
WHERE date >= DATE_SUB(CURDATE(), INTERVAL 1 DAY)
and this
WHERE date > CURDATE()
do the same.
I have another hint: SELECT COUNT(entryID)
and SELECT COUNT(*)
give the same result. SELECT COUNT(*)
gives the database-machine more posibilities to optimize counting, so COUNT(*)
is often (not always) faster than COUNT(field)
.
SELECT COUNT(*)
be slower since *
means all rows? –
Thomson COUNT(primary_id)
is faster. COUNT(*)
can be very slow in a large INNODB table. –
Campeche © 2022 - 2024 — McMap. All rights reserved.
WHERE DAYNAME(date) == CURDATE()
. The problem is thatDAYNAME
returns word form 'Friday'. I need number form so that it can compare withCURDATE()
. – ThomsonSELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY)
returns2012-03-29
, so>= '2012-03-29
is all records from yesterday and today. – ElegiacNOW()
instead ofCURDATE()
– Elegiac