When I ran the SQL query below, the performance is really slow.
There are over 400,000 rows in the table and I have index the CheckDate field.
CheckDate type is datetime
SELECT username, COUNT(*) AS TotalUser
FROM table
WHERE DATE(CheckDate) = CURDATE()
How to improve it?
Try using a range comparison instead of direct equality. In other words, rewrite your query as
or perhaps
See if that helps.
EDIT:
Or the first query could be reworked as
but that starts to get rather ugly, and I’m not sure if negative numbers are allowed in INTERVAL specifiers.
Anyways, the point is that when you find yourself wanting to truncate a date to see if it matches some other date a better option is often to use a ranged comparison. More generally, try to avoid the use of functions on column values in the WHERE clause if there’s any way to avoid it.
Share and enjoy.