We have listings table where we keep all our products. The products have expiry determined by column "ExpiryDate" in the listings table. We want to get all the listings that have expired a day before:
Previous query:
SELECT * from listings
WHERE DATE(ExpiryDate + interval 1 day) = DATE(now());
Modified query:
SELECT * from listings
WHERE ExpiryDate between DATE_FORMAT(now()- interval 1 day, '%Y-%m-%d 00:00:00') and DATE_FORMAT(now() -interval 1 day, '%Y-%m-%d 23:59:59');
I read it somewhere that in "previous query", we can't use indexing on datetime while we can leverage indexing optimization in the "modified query". Is that correct? And is the "modified query" best tuned for performance if we put indexing on column "ExpiryDate"?
Add 1 day to every record, then check if it's the same as now()- you can't use indexes because you're modifying the stored value. Had you written it in a different way -Check if the date is same as (now() minus 1 day)then MySQL can use indexes since it will calculate which numbernow() - 1 daycorresponds to and can use it as comparison base, which is exactly what the second query does. It does not modify theExpiryDatebefore comparing it to a value. It modifies the VALUE it comparesExpiryDateagainst.EXPLAIN,EXPLAIN EXTENDEDand profiling available which you can use for measuring. If yourExpiryDateis adatetimeand if it's indexed, then you should be fine. If it's still slow, it's time to tune the hardware, what resources are available to MySQL (look upinnodb_buffer_pool_size) etc.