Tuesday 31 December 2019

How to optimize database timezones with convert_tz or any other function

I am trying to optimise my mySQL query when handling timezones. My database (mySQL) is set to EET time(+02:00) (I will soon move on AWS where I will use UTC), but in any case, our Cakephp implementation has a setting that retrieves the records as UTC. Our timestamp column his a timestamp type.

So a 2019-12-19 12:44:27 found in our mySQL (+2), is actually 2019-12-19 10:44:27 (UTC) within our CakePHP implementation.

I have created the following query considering a +04:00 timezone.

$company_timezone ='+04:00';
SELECT company_id, COUNT( timestamp ) AS views, url 
FROM behaviour 
WHERE company_id = 1
AND CONVERT_TZ(timestamp,'+00:00','{$company_timezone}')  >= DATE(CONVERT_TZ(NOW(),'+00:00','{$company_timezone}')) 
GROUP BY URL 
ORDER BY views 
DESC LIMIT 20

However this is quite needy in terms of performance. It takes approx 4-5 seconds. Without the convert_tz it takes no more than 0.5 sec.

My question is how can I optimise this? Of course, our timestamp column is indexed, even it doesn't make any sense at the specific query because I use it with convert_tz.

Thank you



from How to optimize database timezones with convert_tz or any other function

No comments:

Post a Comment