Search code examples
phpmysqltimezoneconvert-tz

Mysql timezone and selecting rows from one day


I use MySQL DATETIME column to store date & time. Dates are in UTC. I want to select item from one day. What i'm doing now:

SELECT * FROM data WHERE DATE(CONVERT_TZ(datetime, 'UTC', 'Australia/Sydney')) = '2012-06-01'

note that the timezone depends on user

Problem is that it is quite slow with table growing. Is there any solution how to make it faster?


Solution

  • Currently your query has to compute the conversion for every row of the database. You probably could make things better by converting the other way round, so that the conversion only occurs once (or actually twice, as you'll have to form a range). Then a proper index on datetime should make things pretty fast.

    SELECT * FROM data
    WHERE datetime BETWEEN CONVERT_TZ('2012-06-01 00:00:00', 'Australia/Sydney', 'UTC')
                       AND CONVERT_TZ('2012-06-01 23:59:59', 'Australia/Sydney', 'UTC')
    

    Or if you worry about a 23:60:00 leap second not getting matched by any query, you can do

    SELECT * FROM data
    WHERE datetime >= CONVERT_TZ('2012-06-01', 'Australia/Sydney', 'UTC')
      AND datetime < CONVERT_TZ('2012-06-01' + INTERVAL 1 DAY, 'Australia/Sydney', 'UTC')
    

    In the latter form, you wouldn't have to add the hours PHP-side but instead could simply pass the date as a string parameter.