Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which performs better in a MySQL where clause: YEAR() vs BETWEEN?

I need to find all records created in a given year from a MySQL database. Is there any way that one of the following would be slower than the other?

WHERE create_date BETWEEN '2009-01-01 00:00:00' AND '2009-12-31 23:59:59'

or

WHERE YEAR(create_date) = '2009'
like image 880
abeger Avatar asked Oct 12 '10 19:10

abeger


1 Answers

This:

WHERE create_date BETWEEN '2009-01-01 00:00:00' AND '2009-12-31 23:59:59'

...works better because it doesn't alter the data in the create_date column. That means that if there is an index on the create_date, the index can be used--because the index is on the actual value as it exists in the column.

An index can't be used on YEAR(create_date), because it's only using a portion of the value (that requires extraction).

like image 59
OMG Ponies Avatar answered Sep 20 '22 01:09

OMG Ponies