I have a couple queries which I created 2 separate indexes for, and I understand at the moment it doesn’t really need to use them as the table doesn’t contain that many rows; however they aren’t even listed as a possible key when I use an EXPLAIN.
An example query is:
SELECT
id,eventname,details,datestart,dateend,smallimage
FROM
`events`
WHERE
CAST(dateend AS DATE) >= CURDATE()
AND
(state='VIC' OR state = 'ALL')
AND
STATUS = 1
ORDER BY
datestart ASC;
The alternate query just adds another AND clause before the state, an example being:
AND eventcat = 15
Now, I have added the following two indexes:
KEY `NewIndex4` (`dateend`,`state`,`status`,`datestart`),
KEY `NewIndex5` (`dateend`,`eventcat`,`state`,`status`,`datestart`)
However, MySQL only shows the below index as a possible key:
KEY `NewIndex1` (`state`,`status`,`frontpage`,`image`)
Are my indexes wrong!? Why does it do this?
The problem is that you are doing a CAST on the dateend field. When you perform a function on a field it will not use the index for that field. If possible I would recommend converting this field to a DATE data type. And if the first field in an index is not used, the index will be ignored.
If the field is a DATETIME field, you do not use the CAST function. Simply remove it and leave it as:
Any datetime value that is for today will match. You do not need to remove the time. For example. 2012-12-14 01:00:00 will be greater than or equal to 2012-12-14 (which the CURDATE function will return).