Xaprb

Stay curious!

Benchmarks for DATE operations in MySQL

with 6 comments

This article compares the relative speed of extracting the date part of a value in MySQL with LEFT() and with the DATE() function.

LEFT() is faster than DATE(). To prove this, I inserted two million un-indexed sequential values into a table and selected the minimum and maximum values. Both queries are table scans, so it does read through all the records. The table below lists the time in seconds for MAX() on my computer. I tested with three data types: DATE, TIMESTAMP and DATETIME.

I don’t know why it’s faster to use LEFT() than DATE(). I would assume the reverse to be true, but clearly it’s not, at least on the systems I’ve tested.

The time for MIN() is one or two milliseconds faster than MAX(), probably because the values are sequential and only one assignment is performed, whereas the MAX() query must perform two million assignments.

Written by Xaprb

June 12th, 2006 at 9:16 pm

Posted in SQL

6 Responses to 'Benchmarks for DATE operations in MySQL'

Subscribe to comments with RSS or TrackBack to 'Benchmarks for DATE operations in MySQL'.

  1. I just learned something new: MySQL has a BENCHMARK() function specifically for this type of benchmarking.

    Xaprb

    15 Jun 06 at 8:40 pm

  2. Baron,

    Got here from your recent post that referenced this one. It may be because LEFT() is just string manipulation, but the DATE() function has to extract the date part — it may have to convert the date to an internal representation to extract the date.

    That being said, there should at least be a part of the optimizer that deals with optimizing away something like DATE(col) where col is already in the date format. For instance, SELECT DATE(col) should be optimized to SELECT col when col is in DATE format, so I’d expect that to come back even faster than LEFT().

  3. Yes Baron,

    You are right that LEFT() is a string function thats reason it is faster then DATE().

    Amit Shah

    5 Nov 08 at 6:11 am

  4. [...] 雖然上一篇說明本人偏好unixtime的格式。 但datetime格式還是很好用的。 最大的優點就是在資料章的結果中,可以迅速看出到底是幾年幾月幾日。 今天看到這一篇文章 Benchmarks for DATE operations in MySQL [...]

  5. I agree with that. LEFT() is faster because DATE has to work with locale and l10n related things that LEFT doesn’t. When using LEFT you are directly saying that the Leftomost part of the string is the date, and is the exact format MySQL is expecting it to be.

    Rodrigo

    18 Nov 08 at 4:05 pm

  6. OK that’s fine, but to do LEFT() MySQL has first to convert the value from a date to a string — which has all the locale etc overhead too. Seriously, this cannot be anything but a bug.

    Xaprb

    18 Nov 08 at 6:12 pm

Leave a Reply