Skip to content
Advertisement

MySQL: Why using where on date column does not use index

I have a table which has a column with type Date which is shown like 2020-06-30

I want to find rows where year of the date column is 2020 in them. The problem is even though its indexed, when I run this:

explain select * from table where YEAR(date_c) = 2020;

the key and possible_keys are both null. what should I do?

Advertisement

Answer

You are using a function on the column (YEAR()). That generally precludes the use of an index.

Use direct date comparisons:

where date_c >= '2020-01-01' and date_c < 2021-01-01'

Note: If the date is always in the past, the second part of the comparison is not needed.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement