This consists of two questions:
Is MySQL's timestamp field really faster than datetime field in "order by" query?
If the answer to above question is yes, how much faster it could be? Supposed in a table of 100 million rows and frequently sort a bunch of 100-200k rows based on timestamp field inside MySQL, will the sort time improvement be offseted by converting timestamp to readable string format in outside program?
Timestamps in MySQL are generally used to track changes to records, and are often updated every time the record is changed. If you want to store a specific value you should use a datetime field.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.
Timestamp is a synonym for rowversion, according to the documentation, and it's created automatically and guaranteed1 to be unique. Datetime isn't one of them; it's merely a data type that handles dates and times and may be customised by the client on insert, for example.
Just as DATETIME , the TIMESTAMP data type contains both the date and the time in the following format YYYY-MM-DD hh:mm:ss . However, unlike DATETIME , the TIMESTAMP data type has a fixed range between 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC.
The easiest way to find out is to write a unit test, and actually get some numbers.
My theory was that timestamp would be faster, but according to this blog I am wrong: http://dbscience.blogspot.com/2008/08/can-timestamp-be-slower-than-datetime.html
This is why I tend to get numbers, by profiling, before I decide where to optimize, as my gut feeling can be quite wrong at times.
So, it may depend on the version of MySQL you are using, but it appears that datetime may be faster.
From what I can tell, the major benefit of using TIMESTAMP over DATETIME is being able to automatically set a value to the current time on row creation and being able to set it (or another column with a little effort) to the current time on row update. This allows for an automatic created and modified date.
Because of the other limitations on the TIMESTAMP column (for example, not being to accept dates outside of a certain range or changing if the server time zone changes), DATETIME is going to be preferable if you're not needing one of the two features from above.
However, if you're merely interested in storing a Unix timestamp in the database and not needing the database to ever convert it, you could probably store it as an unsigned integer directly and achieve slightly performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With