SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Apr 2010
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Instead of virtual fields/indexes? -MySQL

    I use MySQL 5.1 where one of the databases is InnoDB.

    I have a datetime field called RecDate which stores '2011-03-03 19:24:00' that is ... always Date through to Minute - no seconds. That is a Primarary Key field. And in most selects it is very fast, but when used in conjunction with DATE(RecDate) it becomes slow. Here is an example:
    SELECT DATE(RecDate), AVG(t) FROM Oa GROUP BY DATE(RecDate)
    or even subsets of data using WHERE MONTH(RecDate) = ...

    From using other databases earlier on I have used tricks like virtual fields or "virtual" indexes. I was hoping I could do something like:
    ALTER TABLE Oa ADD INDEX dateRC(DATE(RecDate))
    or adding a virtual field and building an index on that, but that is is obviously just in the consideration or in the beginning of development for MySQL...

    ... What can I do in the meanwhile?

    Thanks for any suggestions!

    Bagtjesen

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,220
    Mentioned
    58 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by Bagtjesen View Post
    ... What can I do in the meanwhile?
    use an index on the entire datetime column

    performance is impaired only if you use DATE(RecDate) for searching

    so
    Code:
    WHERE DATE(RecDate) = '2022-02-12'
    will require a complete table scan, since you are applying a function to the column value

    however,
    Code:
    WHERE RecDate >= '2022-02-12'
      AND RecDate  < '2011-02-13'
    will use the index most efficiently

    just use the same technique when pulling out a whole month --
    Code:
    WHERE RecDate >= '2022-02-01'
      AND RecDate  < '2011-03-01'
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Member
    Join Date
    Apr 2010
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Rudy,

    Yes, I have been testing while waiting for some explanations (Thanks!), and I have verified that you suggestion works giving the best performance possible.

    Regards,

    Bagtjesen


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •